Here's a program to swap two numbers using three variables with explanation using C Programming language.
#include<stdio.h> //header file #include<conio.h> //header file void main() { int firstnum, secnum, temp; 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); temp = firstnum; firstnum = secnum; secnum = temp; 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 three variables - firstnum and secnum for storing the values of first and second number respectively and temp is for temporary storage (we'll get to that in a minute). 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?
To swap here we use another variable named temp. First we are storing the value of firstnum in temp. Now in the next step we are overwriting firstnum with the value of secnum so that firstnum now holds the value of secnum (half swapping is done). Finally, we store the value of temp (currently holding value of firstnum) into secnum. This is how swapping is done using three variables.
To learn how to swap two numbers using just two variables
How to swap two numbers using only two variables