Write a program to swap the value of two variables without the use third variable.

#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:

  1. a is assigned the sum of a and b i.e. a = a + b.
  2. b is assigned the difference of a and the original value of b i.e. b = a - b. At this point, b holds the original value of a.
  3. a is assigned the difference of the original value of a and the new value of b i.e. a = a - b. At this point, a holds the original value of b.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top