Variable exchange: java exchanges the values of two variables.
How do I exchange the values of two variables? 1. triplicate method: An intermediate variable is used to exchange data.
1 #include<iostream> 2 using namespace std; 3 int main() 4 { 5 int a, b; 6 cin >> a >> b; 7 int c = a; 8 a = b; 9 b = c;10 cout << a << ' '<<b << endl;11 return 0;12 }
2. Without intermediate variables: addition and subtraction
1 #include<iostream> 2 using namespace std; 3 int main() 4 { 5 int a, b; 6 cin >> a >> b; 7 a = a + b; 8 b = a - b; 9 a = a - b;10 cout << a << ' '<< b << endl;11 return 0;12 }
3. without intermediate variables: bitwise (XOR)
1 #include<iostream> 2 using namespace std; 3 int main() 4 { 5 int a, b; 6 cin >> a >> b; 7 a = a^b; 8 b = a^b; 9 a = a^b;10 cout << a << ' '<<b << endl;11 return 0;12 }
4. Only change the output sequence (for algorithm competitions)
1 #include<iostream>2 using namespace std;3 int main()4 {5 int a, b;6 cin >> a >> b;7 cout << b << ' '<<a << endl;8 return 0;9 }