Write a C++ program to swap values of two variables without using third one (logic explained step by step)

Write a C++ program to swap values of two variables without using third one.
Is it possible to swap water of two glass without using third one ?


Steps
User side:
1: User asked to enter the value for first variable 
2: User asked to enter the value for second variable  
3: User displayed the values of variables before and after swapping.
Developer side
1: Declare variables that are going to be used in program.
2: Input the  value for first variable from user.
3: Input the  value for second variable from user.
4: Pass both the values by reference to  function 'swap' and store returned value in the first variable (its not compulsory).
5: In the function add both the values and store the addition in the first variable.
6: Now subtract 'b'(second variable) from 'a' (it contains addition of both values) and store it into 'b'.
7: Now subtract 'b'(second variable) from 'a' (it contains addition of both values) and store it into 'a'.
8: Return the control to the main function .
9: Program end here.

Here is the code:

Code:

#include<iostream>
using namespace std;
int swap(int&, int&);
int main()
{
       int n1 = 0, n2 = 0;
       int& first = n1;
       int& second = n2;
       cout << "Enter First number= ";
       cin >> n1;
       cout << "Enter Second number= ";
       cin >> n2;
       cout << "First number is= " << first << endl;
       cout << "Second number is= " << second << endl;
       first = swap(first, second);
       cout << "After swapping values are " << endl << "First number is= " << first << endl << "Second number is= " << second << endl;
       system("pause");
       return 0;
}

int swap(int& a, int& b)
{
       a = a + b;
       b = a - b;
       a = a - b;
       return a;

}

Output:

Comments