Sunday, November 18, 2012

Tip: Swapping two variables without using third variable

Just a small trick to swap two variables without using the third variable.

Here we go...

Consider the following example

1) int i =10
2) int j=15
3) i=i+j which is 10+15 making it 25. Now, i=25
4) j=i-j which is 25-15 making j=10
5) i=i-j which is 25-10 making i=15

So, you see that following are the values of both i & j after performing  above code logic
i=15 and j=10

Hope this trick helps in any of the scenario

No comments:

Post a Comment