Swap 2 numbers without using third variable
C program to swap two numbers without using third variable.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2, temp;
printf("Enter the numbers to be swapped\t:");
scanf("%d%d", &num1, &num2);
printf("Before Swapping\n num1 = %d\n num2 = %d\n",num1,num2);
// logic for swapping without using third variable
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
printf("\n\nAfter Swapping\n num1 = %d\n num2 = %d\n",num1,num2);
getch();
}
Output
Enter the numbers to be swapped :5
4
Before Swapping
num1 = 5
num2 = 4
After Swapping
num1 = 4
num2 = 5
Explanation
In the above program, we are reading the values of both the numbers in variables named 'num1' and 'num2'.
The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.
Let us understand the above concept with the help of an example.
Let num1 = 5 and num2 = 4
The above statement makes the value of num1 = 5 + 4 = 9
The above statement makes the value of num2 = 9 - 4 = 5
which is equal to the original value of num1. That means, one value is swapped.
The above statement makes the value of num1 = 9 - 5 = 4
which is equal to the original value of num2. That means, both the values are swapped.
The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.
Let us understand the above concept with the help of an example.
Let num1 = 5 and num2 = 4
num1 = num1 + num2;
The above statement makes the value of num1 = 5 + 4 = 9
num2 = num1 - num2;
The above statement makes the value of num2 = 9 - 4 = 5
which is equal to the original value of num1. That means, one value is swapped.
num1 = num1 - num2;
The above statement makes the value of num1 = 9 - 5 = 4
which is equal to the original value of num2. That means, both the values are swapped.