In this tutorial, we are going to learn new program which is Swapping of two numbers and most commonly used in exams or in interviews.
Implementation of this program is very simple.
What is swapping: Swapping of two numbers means replacing the numbers.
How to swap two numbers using the third variable?
For swapping number first we have 2 numbers and using the third variable we swap numbers by doing following steps
Steps for swapping using the third variable
Take two variable with numbers stores in it and one-third variable (a temporary variable )
Variable a, b, temp
1. Copy first variable value in a temporary variable.
temp = a
2. Copy the second variable value in the first variable.
a = b
3. Copy temporary variable value to the first variable.
b = temp
Example
First number = 10
Second number = 20
Temp number
Now swap numbers using above steps
Temp number = First number
=> Temp number = 10
First number = second number
=> First number = 20
Second number = Temp number
=> second number = 10
We got the swapped number as,
First number = 20
Second number = 10
In this way, we implement swapping of two numbers using the third variable
C program swap two number using the third variable
123456789101112131415161718192021222324252627 | #include<stdio.h>void main(){int first,second,temp; //declaring variableprintf(“Enter first\n”);scanf(“%d”,&first); // take input first numberprintf(“Enter second \n”);scanf(“%d”,&second); //take second number inputprintf(“before swaping\n first = %d \n second = %d \n”,first ,second );temp = first ;first = second;second = temp;printf(“after swaping\n first = %d \n second =%d”,first,second);} |
Output :

Explanation
1. First Here we initialized first, second and temp variable
first –> for storing 1st number
second –>for storing the second number
temp ->for storing temporary variable
2. Now here goes the logic(let us take first=10 and second=20)
temp = first , Therefore, temp =10
first = second , Therefore first = 20
second = temp, Therefore second =10
3. Now the values of first and second are 20 and 10
4. The values of first and second after swapping are printed.
Other C language solved programs