Swapping without using a third variable in C++

This program will swap the value of these two numbers without using a temporary variable. The idea behind this concept is very simple. First we will sum the two given numbers and store it in a. Then subtract b from a and store it in b, Again subtract b from a and store it in a. That's all the numbers are swapped

Source code :

#include <iostream>

using namespace std;

int main(){
    
	int a,b;
	
	cout<<"Enter the value of a : ";
	cin>>a;
	
	cout<<"\nEnter the value of b : ";
	cin>>b;
	
	cout<<"\nThe first value is "<<a;
	cout<<" and the second is "<<b<<endl;
	    
	a=a+b;
	b=a-b;
	a=a-b;
	
	cout<<"===  After Swapping  ===\n";
	cout<<"The first value is "<<a;
	cout<<" and the second is "<<b<<endl;
		
    return 0;

}

Output :

Enter the value of a : 10
Enter the value of b : 20
The first value is 10 and the second is 20
===  After Swapping  ===
The first value is 20 and the second is 10

Algorithm :

  1. Declare two variables a,b and get the values from the user
  2. Add a and b and assign it to a ie. a=a+b
  3. Subtract b from a and assign it to b ie. b=a-b
  4. Subtract b from a and assign it to a ie. a=a-b
  5. Print the value of a and b

Output :


                

Comments :