Swap the content of two variables without using a third variable.
#include <iostream>
using namespace std;
int main()
{
//get the two numbers from the user
int n1,n2;
cout<<"Enter the first number: ";
cin>>n1;
cout<<"\nEnter the second number: ";
cin>>n2;
//print the numbers before swapping
cout<<"Before swapping:\n"<<"n1= "<<n1<<"\tn2= "<<n2<<endl;
//swap the numbers
n1 = n1 + n2;
n2 = n1 - n2;
n1 = n1 - n2;
//print the numbers after swapping
cout<<"After swapping:\n"<<"n1= "<<n1<<"\tn2= "<<n2<<endl;
return 0;
}
Comments
Leave a comment