C++ Program to Swap Two Numbers without using third variable

Problem

Write a C++ Program to Swap Two Numbers without using third variable.

Solution

Below is sample source code in C++ to Swap Two Numbers without using third variable. 

#include <iostream>
using namespace std;

int main()
{

    int a,b ;
    cout<<"Enter 1st number: ";
    cin>>a;
    cout<<"\nEnter 2nd number: ";
    cin>>b;

    cout << "\nBefore swapping, Numbers are: " << endl;
    cout << "a = " << a << ", b = " << b << endl;

    a = a + b;
    b = a - b;
    a = a - b;

    cout << "\nAfter swapping, Numbers are: " << endl;
    cout << "a = " << a << ", b = " << b << endl;

    return 0;
}

Output

Enter 1st number:
Enter 2nd number:
Before swapping, Numbers are:
a = 2, b = 1

After swapping, Numbers are:
a = 1, b = 2

%d