1st way – Swap using a third variable which is very common & ordiary
In this tutorial, we are going to see 2nd way to swapping without using third variable
Program to Swap two numbers without using third variable
Using + and –
#include <iostream>
using namespace std;
int main()
{
int a=5, b=10;
cout<<"Before swap a= "<<a<<" b= "<<b<<endl;
a=a+b; //a=15 (5+10)
b=a-b; //b=5 (15-10)
a=a-b; //a=10 (15-5)
cout<<"After swap a= "<<a<<" b= "<<b<<endl;
return 0;
}
Output –
Before swap a= 5 b= 10
After swap a= 10 b= 5
Using / and *
#include <iostream>
using namespace std;
int main()
{
int a=5, b=10;
cout<<"Before swap a= "<<a<<" b= "<<b<<endl;
a=a*b; //a=50 (5*10)
b=a/b; //b=5 (50/10)
a=a/b; //a=10 (50/5)
cout<<"After swap a= "<<a<<" b= "<<b<<endl;
return 0;
}
Output –
Before swap a= 5 b= 10
After swap a= 10 b= 5
For Video Tutorials Subscribe our Youtube Channel
---------------------------------------------------------------------------------------------------------------------------
Previous Page Next Page
Any Doubt ? Feel free to write a comment
Join us on LinkedIn – Great Place of Networking
Follow us on More Together – Facebook for regular updates
Mandatory to join Telegram group for regular job updates
Mandatory to join whatsapp group for regular job updates
Other C++ Programs
For Other Tutorials – Click Here