Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Swap two numbers without using extra variable

Objec­tive:  Write an algo­rithm to swap two num­bers with­out using extra variable.

This is fun puz­zle which is asked in the interview.

Approach:

Exam­ple:

a = 3, b = 5
a = a + b = 8
b = a – b = 8 – 5 = 3
a = a – b = 8 – 3 = 5
Now a = 5, b = 3

Code:

Out­put:

first number: 3 second number: 5
After Swapping: first number: 5 second number: 3

You may also like...