Swap Two Numbers

03-11-17 Course- CPP

This program swaps the value stored in two different variables. To perform this task, third variable is declared.

Program to Swap Numbers (Three Variables are Used)


#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;
}

Output


Before swapping.
a = 5, b = 10

After swapping.
a = 10, b = 5

To perform swapping in above example, three variables are used. You can also perform swapping using only two variables as below:

Source Code to Swap Numbers (Only Two Variables are used)


#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 this program is same as first program above.