Tuesday, September 27, 2016

How to swap two numbers without using a temporary variable?

Here we have two variables:
A = 2, 
B = 3
Now, we swap the value A for 3 and B for 2 without using any temporary variable.

Method 1 (Using Addition and Subtraction)

 A = A + B (A now becomes 5)

 B = A – B (B becomes 2)

 A = A – B (A becomes 3)

Method 1 (Using Multiplication and Division)

 A = A * B (A now becomes 6)

 B = A / B (B becomes 2)

 A = A / B (A becomes 3)

N.B.  Value of B must be garter than 0

Now, we swap the value A for 3 and B for 2 using a temporary variable.

Temp = A

A = B

B = Temp

If there is any other better option,
Please share it here or mail to me arkaa4@gmail.com

Thank You,
Arka Gupta.

No comments:

Post a Comment