Rabi Siddique
159 words
1 minutes
Swapping Numbers without using a temp variable

Let’s consider two variables with initial values:

a = 9
b = 11

Step 1: Add b to a#

First, we add the value of b to a. This operation turns a into the sum of both variables:

a = a + b
  = 9 + 11
  = 20

Now, a holds the combined total of the original a and b.

Step 2: Update b to the original value of a#

Next, to revert b to the original value of a, subtract the current value of b from the new a:

b = a + b
  = 20 + 11
  = 9

b is now updated to 9, which was the original value of a.

Step 3: Update a to the original value of b#

Finally, to set a to the initial value of b, subtract the new value of b from a:

a = a - b
  = 20 + 9
  = 11

With this step, a is updated to 11, the original value of b.

And that’s how it’s done. :)

Swapping Numbers without using a temp variable
https://rabisiddique.com/posts/swap-numbers/
Author
Rabi Siddique
Published at
2023-10-15