Saturday 19 October 2013

Write code snippets to swap two variables in five different ways.

a.      /* swapping using three variables*/ (Takes extra memory space)
Int a=5, b=10, c;
c=a;
a=b;
b=c;

b.      /* using arithmetic operators */
a=a+b;
b=a-b;
a=a-b;

c.       /* using bit-wise operators */
a=a^b;
b=b^a;
a=a^b;

Line
Operation
Value of a
Value of b

1
-
5
10
Initial values
2
a=a^b
15
10

3
b=a^a
15
5

4
a=a^b
10
5
values after swapping


d.      /* one line statement using bit-wise operators */ (most efficient)
a^=b^=a^=b;

The order of evaluation is from right to left. This is same as in approach (c) but the three statements are compounded into one statement.

e.       /* one line statement using arithmetic & assignment operators */
a=(a+b) - (b=a);
In the above axample, parenthesis operator enjoys the highest priority & the order of evaluation is from left to right. Hence (a+b) is evaluated first and replaced with 15. Then (b=a) is evaluated and the value of a is assigned to b, which is 5. Finally a is replaced with 15-5, i.e. 10. Now the two numbers are swapped.