Write a program of c++ swapping two variables without using the third variable. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Write a program of c++ swapping two variables without using the third variable.

1st Apr 2017, 5:14 AM
Tehreem
4 Answers
+ 5
In 3 ways you can do it, let you have x , y as your 2 variable, first approach:- x=x+y; y=x-y; x=x+y; second approach:- x=x*y; y=x/y; x=x/y; third approach:- x=x^y; y=x^y; x=x^y;
1st Apr 2017, 7:19 AM
Nikhil Dhama
Nikhil Dhama - avatar
+ 4
1st Apr 2017, 9:01 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 3
If we have two variables x and y, then we can do this: x = x + y y = x - y x = x - y I'm not just going to write the program, by the way. This should be enough.
1st Apr 2017, 5:27 AM
DaemonThread
DaemonThread - avatar
+ 1
swap(x,y) in algorithm header works with move semantics (C++11) so it changes addresses of x and y.
1st Apr 2017, 11:59 AM
Amir Hossein Farzin
Amir Hossein Farzin - avatar