Wednesday, February 13, 2008

How to swap numbers

Some student asked me to help him with this program to swap two numbers. So I thought it might be good to post it here as well...

 

There are two methods of swapping 2 numbers.

1. Using a third temporary variable

2. Without using a third variable

 

Let's discuss both of them...

By using a temporary variable

Say you need to swap Var1 and Var2, then create a third variable (say Var3) and use following syntax...

Var3 = Var2

Var2 = Var1

Var1 = Var3

 

See, it's easy. Now let's talk about a little tricky method...

Without Using a temporary Variable

If you have to swap Var1 and Var2, use the following technique...

Var1 = Var1 + Var2

Var2 = Var1 - Var2

Var1 = Var1 - Var2

 

Have fun

0 comments: