C Program to swap 2 numbers using third variable



#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,swap;
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");
swap=a;
a=b;
b=swap;
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. We are using here third variable swap. Firstly we assign the value of variable a in the temporary variable swap the value of variable a is now secured in the temporary variable swap. After that we assign the value of variable 'b' into the variable 'a' it means now variable a is containing the value of variable b. Now we assign the secure value of variable 'a' that is present in the variable swap into the variable b. In this way we can swap the value of two variables by using third variable. Now we are printing the swapped values of a and b by using printf statement. You can understand this process with the help of this example:

a=5
b=4
swap=a means swap=5
a=b means a=4
b=swap means b=5
so now
a=4
b=5
The output of the above program is given below:

Output:

c program