C++ Program to swap two numbers without third variable
We can swap two numbers without using third variable. There are two common ways to swap two numbers without using third variable:
- By using + and - operators.
Program:
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<"a=";
cin>>a;
cout<<"b=";
cin>>b;
a=a+b;
b=a-b;
a=a-b;
cout<<"After swap:"<<endl;
cout<<"a="<<a<<" b="<<b;
return 0;
}
Output:
a=10
b=20
After swap
a=20 b=10
2. By using * and / operators.
Program:
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<"a=";
cin>>a;
cout<<"b=";
cin>>b;
a=a*b;
b=a/b;
a=a/b;
cout<<"After swap:"<<endl;
cout<<"a="<<a<<" b="<<b;
return 0;
}
Output:
a=10
b=20
After swap
a=20 b=10
C++ Program to two swap two numbers without using third variable
Reviewed by Beast Coder
on
February 01, 2021
Rating:
No comments: