Life of student

All about Programming , C++ ,Fedora

  • Blog Stats

    • 16,886 hits
  • Categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email. I too can't see who had subscribed my blog :(

    Join 11 other followers

  • Advertisements

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


here is using bitwise operator.



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


8 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:
    I blog At :

  2. pankaj4u4m said


  3. Shubham said

    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

  6. Techycage said

    This link might help you …swapping of two numbers

  7. Maha said

    Thank you

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

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: