Swap two numbers without using extra variable

Objective:  Write an algorithm to swap two numbers without using extra variable.

This is fun puzzle which is asked in the interview.

Approach:

Example:

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:

Output:

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

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: