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