Thursday, February 15, 2007

Swap values of three variables without using fourth variable

       In my recent interview, a well known company in ahmedabad having branches in all over India, I was asked to write a programm. I have to swap the values of three variables without using fourth varable.  I found it really triky. I will first explain this with two variables and than show for three variables in two diffrent ways.

                 Lets, consider the case    a = 10 and b=20. I have to write the programm so that result will be a= 20 and b= 10. Below is the steps,

a = 10;
b=20;
a = a+b; ( a= 30)
b = a - b; (b = 30 - 20 =10)
a =  a-b; (a = 30-10 = 20)

Fig - 1 Steps to swap the values of two variables.

     Now take three variables, a= 10, b=20 and c =30. The output should be a=30, b=10 and c= 20. First way to achive this is you can use steps mentioned in Fig -1 three times. First swap a and b than a and c. Below is the steps,

 

a = 10;
b=20;
c=30;


a = a+b; ( a= 30)
b = a - b; (b = 30 - 20 =10)
a =  a-b; (a = 30-10 = 20)

// Here a= 20 and b= 10;

a = a+c; ( a= 20 + 30 = 50)
c = a - c; (c = 50 - 30 =20)
a =  a-c; (a = 50-20 = 30)

// Here a= 30 and c= 20;

Fig - 2 Steps to swap the values of three variables.

 

Second way of swapping the values of three variable is,

a = 10;
b=20;
c=30;


a = a+b+c;  ( a= 60)
b = a - (b+c);  (b = 60 - (20+30) =10)
c =  a- (b+c);  (c = 60 - (10 + 30) = 20)
a = a- (b+c);   (a = 60 - (10 + 20) = 30)

Fig - 3 Steps to swap the values of three variables.

Happy Programing.

1 comment:

vivianzjl said...

Hello! Mozilla Firefox web browser has updated,Please visit my blog,Free download Quickly