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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.