C++ Program to Swap Two Numbers

107
views
C++ Program to Swap Two Numbers

This example contains two different techniques to swap numbers in C++ programming.

The first program uses a temporary variable to swap numbers, whereas the second program doesn’t use temporary variables.

To understand this example, you should have the knowledge of  C++ programming 

Program to Swap Numbers (Using 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;
}

Output

Before swapping.
a = 5, b = 10

After swapping.
a = 10, b = 5

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.

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

Program to Swap Number Without Using Temporary Variables

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

Output

Before swapping.
a = 5, b = 10

After swapping.
a = 10, b = 5

Related Programs

Ask your questions and clarify your/others doubts about swapping Two Number by commenting. Documentation

Please write to us at [email protected] to report any issue with the above content or for feedback.