C Program to swap 2 numbers without using third variable



#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter the value of a:");
scanf("%d",&a);
printf("\nEnter the value of b:");
scanf("%d",&b);
printf("\n........Swap the value of a and b..............\n");
a=a+b;
b=a-b;
a=a-b;
printf("\nValue of a and b after swapping:\n");
printf("\na=%d",a);
printf("\nb=%d",b);
getch();
}

Explanation:

The above program is responsible for swapping the values present in two variables a and b. User can enter the values in these variables at runtime with the help of scanf statement. Here we are not using any temporary variable for swapping the values. We are swapping the values present in variable 'a' and 'b' by applying some simple arithmetic operations. Firstly we assign the addition of 'a' and 'b' into the variable a. After that we assign the subtraction of a (Now it contains sum of previous value of 'a' and the second variable b) and b into the variable b. Now b contains the previous value of a. Finally we assign the subtraction of a and b into the variable a. Now variable 'a' contains the previous value of b. In this way we can swap the value of two variables without using third variable. You can understand this process with the help of this example:

a=5
b=4
a=a+b=9
b=a-b=5
a=a-b=4
so now
a=4
b=5
The output of the above program is given below:

Output:

c program