If you’re a beginner in programming or just learning C language, swapping two numbers without using a third variable may seem like a daunting task. However, it’s a simple process that can be achieved with just a few lines of code.
Why Swap Two Numbers Without a Third Variable?
Before we dive into the code, let’s first understand why we would want to swap two numbers without using a third variable. The answer is simple: to save memory space. In certain applications, every byte of memory matters, and using an extra variable to swap two numbers may not be practical. Therefore, we need a way to swap the numbers without using any extra memory.
Algorithm to Swap Two Numbers
To swap two numbers without using a third variable, we can use the following algorithm:
- Read the values of the two numbers, A and B, from the user.
- Add A and B and store the result in A.
- Subtract B from A and store the result in B.
- Subtract A from B and store the result in A.
- Print the swapped values of A and B.
Let’s implement this algorithm in C.
Code to Swap Two Numbers Without Using a Third Variable in C
#include <stdio.h>
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// swapping without using third variable
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
printf("After swapping, num1 = %d, num2 = %d", num1, num2);
return 0;
}
Let’s understand how this code works.
First, we read two integers num1
, num2
from the user using scanf()
. Then, we perform the swap using the algorithm mentioned above. Note that in line 8, we add num1
and num2
and store the result in num1
. This is because num1
now contains the sum of the two numbers, which we can use to find the difference between them.
Next, we subtract num2
from num1
and store the result in num2
. This is because num2
now contains the difference between the sum of the two numbers and the original value of num2
, which is equal to the original value of num1
.
Finally, we subtract num1
from num2
and store the result in num1
. This is because num1
now contains the difference between the sum of the two numbers and the original value of num1
, which is equal to the original value of num2
.
After the swap is complete, we print the swapped values of num1
and num2
using printf()
.
Conclusion
Swapping two numbers without using a third variable is a simple and efficient process that can save memory space in certain applications. In C, we can achieve this by using a simple algorithm and a few lines of code. We hope this article has helped you understand how to swap two numbers without using a third variable in C.