## swapping of two numbers in one line

Posted by pankaj4u4m on August 12, 2009

Today when i was programming I saw one interesting thing, swapping of two numbers in one line!!!!

Previously I know how to swap two numbers usins bitwise operator but this is simple using ordinary operation…:)

a=(b=(a=b+a,a-b),a-b);

here is using bitwise operator.

a^=b^=a^=b;

Explanation:

1.For first expression if we seperate the expression it will like this-

First a=a+b will evaluate thusand then if we subtract b from a now it will give the original value of a and is assigned to b. So now b contain the value of a. In next after assigning a to b again subtract b from a i.e this time it will give the original value of b and is assigned to a. So the result is a contain the valuse of b and b contain the value of a i.e swapped.

ex: a=3;b=2;

a=a+b =>a=5;

b=a-b =>5-2 =>b=3 (original value of a)

a=a-b =>5-3 =>a=2(original value of b)

2. For second expression:

lets understand with an example. a=3 ,b=2;

if we convert it into binary form a=11,b=10;

so in first step a=a^b => 11(XOR)10 =>01(now value of a)

in next b=b^a => 10(XOR)01 => 11(now value of b and original value of a)

next a=a^b => 01(XOR)11 => 10 (now value of a original value of b)

so it is swapped. 🙂

## Ram Kumar.K said

hai pankaj i am doing my 3 rd B.Tech IT in Kongu Engg Coll.. Your Blog is superb… I found you in ILugc… Keep rocking…

My email is: ramkumarit2007@gmail.com

I blog At : fallinlinux.wordpress.com

## pankaj4u4m said

thanks…

## Shubham said

b=b-(a=((b=a+b)-a));

this does the same too…

your code is also good anyway.

## yellowise said

b=a+b -(a=b); does the same too!

## sagarkadamblog said

thanks

## Techycage said

This link might help you …swapping of two numbers

## Maha said

Thank you

## AMU Student Login said

Hey great post! I hope it’s alright that I shared it on my Twitter,

if not, no worries just tell me and I’ll remove it.

Regardless keep up the great work.