Google News
logo
C++ Program to Swap Two Numbers
In the following example contains two different techniques to swap numbers in C programming. The first program uses temporary variable to swap numbers, whereas the second program doesn't use temporary variables.

Example 1: Swap Numbers (Using Temporary Variable) :

Program :
#include <iostream>
using namespace std;

int main()
{
    int a = 7, b = 12, 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;
}
Output :
Before swapping.
a = 7, b = 12

After swapping.
a = 12, b = 7
* To perform swapping in above example, three variables are used.

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

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

* You can also perform swapping using only two variables as below.

Example 2 : Swap Numbers Without Using Temporary Variables :

Program :
#include <iostream>
using namespace std;

int main()
{
    
    int a = 7, b = 12;

    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;
}
Output :
Before swapping.
a = 7, b = 12

After swapping.
a = 12, b = 7
Let us see how this program works :

* Initially, a = 7 and b = 12.

* Then, we add a and b and store it in a with the code a = a + b. This means a = 7 + 12. So, a = 19 now.

* Then we use the code b = a - b. This means b = 19 - 12. So, b = 7 now.

* Again, we use the code a = a - b. This means a = 19 - 7. So finally, a = 12.

Hence, the numbers have been swapped.