Swapping two numbers is a common programming problem often asked in coding interviews and exams. While the traditional approach uses a temporary variable, there are multiple ways to swap two numbers without using an extra variable. In this article, we will explore different methods to achieve this efficiently.
Using a third variable for swapping is straightforward but not always efficient. Avoiding an extra variable helps in optimizing memory usage and demonstrates a better understanding of algorithmic logic. This is particularly useful in competitive programming and low-memory environments.
One of the simplest ways to swap two numbers without a temporary variable is by using addition and subtraction.
#include <stdio.h>
int main() {
int a = 5, b = 10;
printf("Before swapping: a = %d, b = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
a = a + b
→ a becomes 15 (5+10)b = a - b
→ b becomes 5 (15-10)a = a - b
→ a becomes 10 (15-5)Bitwise XOR is a highly efficient way to swap numbers without using extra memory.
#include <stdio.h>
int main() {
int a = 5, b = 10;
printf("Before swapping: a = %d, b = %d\n", a, b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
a = a ^ b
→ stores bitwise XOR of a and b in a.b = a ^ b
→ restores original value of a into b.a = a ^ b
→ restores original value of b into a.Another alternative is using multiplication and division.
#include <stdio.h>
int main() {
int a = 5, b = 10;
printf("Before swapping: a = %d, b = %d\n", a, b);
a = a * b;
b = a / b;
a = a / b;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
a = a * b
→ stores product of a and b in a.b = a / b
→ restores original value of a into b.a = a / b
→ restores original value of b into a.Swapping two numbers without using a third variable is an essential concept in programming. Understanding multiple methods helps in writing optimized code suitable for different scenarios. If you’re preparing for coding interviews, practicing these techniques will enhance your problem-solving skills.