C++ gurus and learners, we program ourselves :P all work is CC licensed

Wednesday, November 6

Swapping without use of third variable

Swapping means to interchange values of usually two variables and is done using third temp variable e.g.
int var1 = 10, var2 = 20;
int temp = var2;
var2 = var1;
var1 = temp;
//now var1 = 20 and var2 = 10
//hence values have been swapped

But take a look at code swapping without use of third variable, this trick will come handy in future assignments

int var1 = 10, var2 = 20;
var1 = var1 * var2;
var2 = var1 / var2;
var1 = var1 / var2;
//now var1 = 20 and var2 = 10
//hence values have been swapped

For the person who can explain this code to me and post a solution using (^) operator, there is a GENUINE MICROSOFT VISUAL STUDIO KEY ;)
You can post a request for guest post in comments, anywhere

8 comments :

  1. here is how to swap with additions
    int a,b;
    a=a+b;
    b=a-b;
    a=a-b;
    simple

    ReplyDelete
  2. Addition : var1 = var1 + var2;
    Subtraction : var2 = var1 - var2;

    ReplyDelete
  3. yara addition and subtraction wala code bhi share karo

    ReplyDelete
  4. @Saad Abdullah Munir please paste code in comment or mail it to fmswwx@gmail.com and we will get it posted

    ReplyDelete
  5. great yaar please share the code with us, you will get a special referral on post

    ReplyDelete
  6. i have done this program but using addition and subtraction logic..

    ReplyDelete