Be the first user to complete this post

  • 0
Add to List
Beginner

225. Swap two numbers without using extra variable

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

This is a fun puzzle that 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

Output:

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