C # basic learning notes-algorithm: exchange,

Source: Internet
Author: User

C # basic learning notes-algorithm: exchange,

Switching the values of two variables is like switching the drinks in two cups: A cup of full milk and a cup of full coffee. How can this be exchanged?

The same is true for variable exchange. The exchange of two variables also requires an "empty cup", that isIntermediate variable:

1 string a = "zhengang"; // The first variable 2 string B = "wenfeng"; // the second variable 3 string temp; // The intermediate variable 4 // the first step: assign variable a to the intermediate variable 5 temp = a; // as if the milk is poured into the empty cup 6 // Step 2: Assign variable B to variable a 7 a = B; // as if the coffee is poured into the milk cup 8 // Step 3: Assign the intermediate variable to the variable B 9 B = temp; // as if the milk in the empty cup is poured into the coffee cup 10 // at this time, the exchange is complete, variable a stores "Wen Feng", and B stores "Zhen gang"

The steps to solve the actual problem are called"AlgorithmExchange is the most common algorithm.

For example:

1 namespace Test 2 {3 class Program 4 {5 static void Main (string [] args) 6 {7 string boy = "beauty "; // boy name 8 string girl = "Wei Qiang"; // girl name 9 string temp; // The intermediate variable 10 temp = boy; // assign the boy's name to temp11 boy = girl; // assign the girl's name to boy 12 girl = temp; // assign the name in temp to girl 13 Console. writeLine ("boy called" + boy + "girl called" + girl); 14} 15} 16}

The running result is:

The above is taken from MOOC course C # getting started with development

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.