This is very common question asked in interview to programmer, how to swap value of variables without using the third variables?
As we know, it is easy to swap two variables with the help of the third variables (see example in C language)
Example to swap values with the help of third variable:
void main()
{
int a, b, c;
a=5;
b=10;
printf(“Value of a: %d \nValue of b: %d”, a, b);
c=a;
a=b;
b=c;
printf(“Value of a: %d \nValue of b: %d”, a, b);
}
In above example, The value of “a” is 5 and value of “b” is 10. Now we are using the variable “c” to store the value of a (c=a;), in next line we overwrite the variable “a” with the value of “b” and save the value of “c” which store the value of “a” in variable “b”.
Example to swap values without using third variable:
void main()
{
int a, b;
a=6;
b=12;
printf(“Value of a: %d \nValue of b: %d”, a, b);
a=a+b;
b=a-b;
a=a-b;
printf(“Value of a: %d \nValue of b: %d”, a, b);
}
In this example, there is no third variable, we are using some calculation to swap the variables. First we add the both variable in “a” (a=a+b) i.e. a=18, then deduct the second variable with total value (b = a-b) i.e. b = 6, then deduct again from a to b (a=a-b) i.e. a=18-6 which is twelve;
Recent Comments