Write a C program to swap two numbers in variables a and b. Accept these values from the user.
This is one of the most popular and easiest program. We can do this in two ways, with and without using third variable and you will learn both. 😃
Tutorial 📺
Watch the tutorial and understand how to solve this problem 😉
Steps 🪜
C Program to Swap Two Numbers without third variable
- Display a message to the user and accept two numbers.
- Store the accepted values in two variables n1 and n2.
- Display the values of both variables before swapping.
- First, store the addition of n1 and n2 in variable n1 (n1 = n1 + n2).
- Next, store the difference of n1 and n2 in variable n2 (n2 = n1 – n2).
- Finally, store the difference of n1 and n2 in variable n1 (n1 = n1 – n2).
- Now, display the values of both variables after swapping.
C Program to Swap Two Numbers using third variable
- Display a message to the user and accept two numbers.
- Store the accepted values in two variables n1 and n2.
- Display the values of both variables before swapping.
- First, store the value of n1 in the third variable temp (temp = n1).
- Next, store the value of n2 in variable n1 (n1 = n2).
- Finally, store the value of temp in variable n2 (n2 = temp).
- Now, display the values of both variables after swapping.
Flow Chart 🌻
Flow chart to swap 2 numbers without third variable

Flow chart to swap 2 numbers using third variable

Code 💻
Swap 2 numbers without using third variable
#include<stdio.h>
void main()
{
int n1=0, n2=0;
printf("Please enter two numbers: ");
scanf("%d%d", &n1, &n2); // suppose user entered n1=10 and n2=20
printf("\nBefore swapping:\n\n n1 = %d and n2 = %d", n1, n2);
// Swap without using third variable
n1 = n1 + n2; // n1 = 10 + 20 = 30
n2 = n1 - n2; // n2 = 30 - 20 = 10
n1 = n1 - n2; // n1 = 30 - 10 = 20
printf("\n\nAfter swapping:\n\n n1 = %d and n2 = %d", n1, n2);
}
Swap 2 numbers using third variable
#include<stdio.h>
void main()
{
int n1=0, n2=0, temp=0;
printf("Please enter two numbers: ");
scanf("%d%d", &n1, &n2); // suppose user entered n1=10 and n2=20
printf("\nBefore swapping:\n\n n1 = %d and n2 = %d", n1, n2);
// Swap using third variable - temp
temp = n1; // temp = 10
n1 = n2; // n1 = 20
n2 = temp; // n2 = 10
printf("\n\nAfter swapping:\n\n n1 = %d and n2 = %d", n1, n2);
}
Examples 😍
Let’s assume that the user enters two numbers -3 and 5.
Output will be like:
Before swapping:
n1 = -3 and n2 = 5
After swapping:
n1 = 5 and n2 = -3
Let’s take another example where the user enters two numbers 10 and 20.
Output will be like:
Before swapping:
n1 = 10 and n2 = 20
After swapping:
n1 = 20 and n2 = 10
This is how we swap two numbers with or without using third variable. 😎
For more C programs, click here.
Comments