Join super friendly code & developer communities

A place for coders and developers to share, learn and grow together.

Swapping two variables without using third variable in programming

I am going to write a different ways below to swap two variables. I know this is the easiest and one of the first program anyone does when they first start programming. But here I am going to write 3 different ways to swap variable without using third variable. That makes it 4, i.e there are 4 different ways to swap variables, including using third variable to swap. I am going to write program in python for easy understanding.

For those who are new to programming, here's how you swap two variables.

#Program to swap two variables using a third variable.

#init variables
a = 1
b = 2

#swap
c = a
a = b
b = c

print (a) #prints 2
print (b) #prints 1

The above program is a very basic program by using a third variable to swap.

Lets see how to swap variables without using a third variable.

Method 1 

Using arithmetic operators plus(+) and minus(-).

#Program to swap two variables without using a third variable.

#init variables
a = 1
b = 2

#swap
a = a + b
b = a - b
a = a - b

print (a) #prints 2
print (b) #prints 1

Yay! It works! 

Method 2

Using arithmetic operators multiplication(*) and division(/).

#Program to swap two variables without using a third variable.

#init variables
a = 1
b = 2

#swap
a = a * b
b = a / b
a = a / b

print (a) #prints 2
print (b) #prints 1

And It works too!

Sure. It does work! But there's one problem in both programs above. For larger numbers it may result in arithmetic overflow. The second method may not work in case one of the numbers is 0.

Note: Arithmetic overflow is caused when the result of calculation exceed the memory space for the variable.

Method 3

Using bitwise XOR(^) operator.

#Program to swap two variables without using a third variable.

#init variables
a = 1
b = 2

#swap
a = a ^ b
b = a ^ b
a = a ^ b

print (a) #prints 2
print (b) #prints 1

💥Boom! It works.

I wrote the post in python for easy understanding but the above concepts can be applied to other programming languages too.

P.S. If you have any questions, click here to join our community and feel free to ask any questions.

Share:
Super friendly <br/>code & developer communities

Super friendly
code & developer communities

A place for coders and developers to share, learn and grow together.