How to swap two numbers without using 3rd variable..? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to swap two numbers without using 3rd variable..?

Suppose x=2 and y=4. How will you make y=2 and x=4 without using any third variable??

26th Jun 2017, 4:32 AM
Roopansh Pawar
Roopansh Pawar - avatar
4 Answers
+ 1
x=x+y y=x-y x=x-y as x=2 and y=4 x=x+y= 2+4=6 y=x-y= 6-4=2 x=x-y= 6-2=4 you can check it on any input
26th Jun 2017, 4:46 AM
kshitij kumar
kshitij kumar - avatar
0
y = x + y x = y - x y = y - x
26th Jun 2017, 4:50 AM
M0H4MM4D
M0H4MM4D - avatar
0
You can also use XOR. x = x ^ y; y = y ^ x; x = x ^ y;
26th Jun 2017, 4:54 AM
ChaoticDawg
ChaoticDawg - avatar
0
x, y = y, x
26th Jun 2017, 6:05 AM
Nomeh Uchenna Gabriel
Nomeh Uchenna Gabriel - avatar