C++ Example - Swap Two Numbers

C++ Examples

Below we use two methods to swap two variables: using a temporary variable and without using a temporary variable.

Example - Using a Temporary Variable

#include <iostream> using namespace std; int main() { int a = 5, b = 10, temp; cout << "Before swapping:" << endl; cout << "a = " << a << ", b = " << b << endl; temp = a; a = b; b = temp; cout << "\nAfter swapping:" << endl; cout << "a = " << a << ", b = " << b << endl; return 0; }

The output of the above program is:

交换之前:
a = 5, b = 10

交换之后:
a = 10, b = 5

Example - Without Using a Temporary Variable

#include <iostream> #include <iostream> using namespace std; int main() { int a = 5, b = 10; cout << "Before swapping:" << endl; cout << "a = " << a << ", b = " << b << endl; a = a + b; b = a - b; a = a - b; cout << "\nAfter swapping:" << endl; cout << "a = " << a << ", b = " << b << endl; return 0; }

The output of the above program is:

交换之前:
a = 5, b = 10

交换之后:
a = 10, b = 5

C++ Examples

other extensions