Program to Swap Two Numbers in C++

This example contains two different techniques to swap numbers in C++. The first program uses a temporary variable to swap numbers, whereas the second program doesn't use temporary variables.



Example 1: Swap Numbers (Using Temporary Variable)


  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int a = 4, b = 10, temp;
  6. cout << "Before swapping." << endl;
  7. cout << "a = " << a << ", b = " << b << endl;
  8. temp = a;
  9. a = b;
  10. b = temp;
  11. cout << "\nAfter swapping." << endl;
  12. cout << "a = " << a << ", b = " << b << endl;
  13. return 0;
  14. }

Output

Before swapping.
a = 4, b = 10

After swapping.
a = 10, b = 4
To perform swapping in the above example, three variables are used.

The contents of the first variable are copied into the temp variable. Then, the contents of the second variable are copied to the first variable.

Finally, the contents of the temp variable are copied back to the second variable which completes the swapping process.

Example 2: Swap Numbers Without Using Temporary Variables.


  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int a = 4, b = 10;
  6. cout << "Before swapping." << endl;
  7. cout << "a = " << a << ", b = " << b << endl;
  8. a = a + b;
  9. b = a - b;
  10. a = a - b;
  11. cout << "\nAfter swapping." << endl;
  12. cout << "a = " << a << ", b = " << b << endl;
  13. return 0;
  14. }

Output

Before swapping.
a = 4, b = 10

After swapping.
a = 10, b = 4

Check out these related examples:



Share:
spacer

No comments:

Post a Comment