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

Showing posts with label swapping in three steps. Show all posts
Showing posts with label swapping in three steps. Show all posts

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