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
#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; }
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
a
and b
and assign it to a
ie. a=a+b
b
from a
and assign it to b
ie. b=a-b
b
from a
and assign it to a
ie. a=a-b
Comments :