Saturday, 15 November 2014

Programming Math tricks, swapping!

Swapping values of two variables without creating a new one!


Consider:

a = 10;
b = 5;

Swap it without making a new variable. Can you?

This is a really challenging task for some people. In my class it was hard for almost all of us but the
answer is really simple.

You simply do:

a = a + b;
b = a - b;
a = a - b;

and the values are swapped! :)

Same can be done with arrays:

array[1] = array[1] + array[2];
array[2] = array[1] - array[2];
array[1] = array[1] - array[2];

Good? Share please!

No comments:

Post a Comment