Here's a program to swap two numbers using only two variables with explanation using C Programming language.
#include<stdio.h> //header file #include<conio.h> //header file void main() { int firstnum, secnum; clrscr(); printf("Enter the first number"); scanf("%d",&firstnum); printf("Enter the second number"); scanf("%d",&secnum); printf("First Num is %d\nSecond num is %d, firstnum, secnum); firstnum= firstnum + secnum; secnum= firstnum - secnum; firstnum= firstnum - secnum; printf("After Swapping...\nFirst Num is %d\nSecond num is %d, firstnum, secnum); getch(); }
Explanation of above program
In the above code, first we included the header file then inside main we declared two variables - firstnum and secnum for storing the values of first and second number respectively. Next we prompt the user to enter two numbers after which we are printing those numbers out for the user. After that we are doing the swap.
How swapping is done using just two variables?
First we are storing the sum of both numbers in firstnum. Then we are subtracting the value of secnum from the new value of firstnum and by this now secnum holds the value of firstnum that user has entered (half swapping is done). Now we are again subtracting firstnum and new value of secnum and storing it in firstnum resulting in complete swapping. In this way the swapping is done using just two variables.
Lets understand with an example
If you ain't able to understand the above program don't worry lets look at an example:
Suppose, currently firstnum = 10 and secnum = 15. After performing the first step i.e.
firstnum= firstnum + secnum;firstnum = 10 + 15 = 25. i.e. firstnum now has a value of 25. After second step i.e.
secnum= firstnum - secnum;secnum = 25 - 15 = 10 i.e. secnum now has a value of 10 i.e. original value of firstnum. After performing the last step i.e.
firstnum= firstnum - secnum;firstnum = 25 - 10 = 15 i.e. firstnum now has a value of 15 i.e. original value of secnum. Hence the numbers are finally swapped using just two numbers.