Swap without a temp variable

It’s possible with addition:

#include<iostream>
using namespace std;

int main(){

int x=10,y=15;
cout<<"Before swapping: x="<<x<<"y="<<y<<endl;
x=x+y; //25
y=x-y; //25-15=10
x=x-y; //25-10=15

cout<<"After swapping: x="<<x<<"y="<<y<<endl;
return 0;
}

It’s also possible with multiplication:

#include<iostream>
using namespace std;

int main(){

int x=10,y=15;
cout<<"Before swapping: x="<<x<<"y="<<y<<endl;
x=x*y; //25
y=x/y; //25-15=10
x=x/y; //25-10=15

cout<<"After swapping: x="<<x<<"y="<<y<<endl;
return 0;
}

 

 

 

Source:
http://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *