Life of student

All about Programming , C++ ,Fedora

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. :)

About these ads

5 Responses to “swapping of two numbers in one line”

  1. 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

  2. pankaj4u4m said

    thanks…

  3. Shubham said

    b=b-(a=((b=a+b)-a));
    this does the same too…
    your code is also good anyway.

  4. yellowise said

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

  5. thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: