In this tutorial, we will write a C program to swap two numbers without using a temporary variable. There are two ways to swap variables.
- Using + and –
- Using * and /
Let us go through each of them with a C program. You may check out the following program.
C Program to Swap Two Numbers without using Third Variable
1. Using + and –
#include<stdio.h>
int main()
{
int a, b;
printf("Enter a: ");
scanf("%d", &a);
printf("Enter b: ");
scanf("%d", &b);
a = a + b; //a = 10 + 20 = 30
b = a - b; //b = 30 - 20 = 10
a = a - b; //a = 30 - 10 = 20
printf("The swapped values a: %d and b: %d", a, b);
return 0;
}
Output:
Enter a: 10
Enter b: 20
The swapped values a: 20 and b: 10
2. Using * and /
#include<stdio.h>
int main()
{
int a, b;
printf("Enter a: ");
scanf("%d", &a);
printf("Enter b: ");
scanf("%d", &b);
a = a * b; //a = 10 * 20 = 200
b = a / b; //b = 200 / 20 = 10
a = a / b; //a = 200 / 10 = 20
printf("The swapped values a: %d and b: %d", a, b);
return 0;
}
Output:
Enter a: 10
Enter b: 20
The swapped values a: 20 and b: 10
Note that the swapping using / and * will not work if one of the swapping values is zero (0).