#include<stdio.h>
#include<conio.h>
int main()
{
int a=7,b=4;
printf("\n A=%d B=%d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nNow A=%d B=%d",a,b);
getch();
}
/*In the above program,no third variable is used as a mediator for swapping the values.*/
This program swaps the values of variables a
and b
without using a third variable.
First, the values of a
and b
are initialized to 7
and 4
, respectively. Then, the values of a
and b
are swapped using the following steps:
a
is assigned the sum ofa
andb
i.e.a = a + b
.b
is assigned the difference ofa
and the original value ofb
i.e.b = a - b
. At this point,b
holds the original value ofa
.a
is assigned the difference of the original value ofa
and the new value ofb
i.e.a = a - b
. At this point,a
holds the original value ofb
.
Finally, the program prints the values of a
and b
, which are swapped, by using the printf()
function.
Thanks
Write a program to swap the value of two variables without the use third variable.