📘 Lesson · Lesson 61
Swap Without Third Variable
Swap Without Third Variable
The Trick
💡 Note
You can swap two numbers without a temporary variable using arithmetic or XOR.
Using Arithmetic
C
#include <stdio.h>
int main() {
int a = 5, b = 9;
a = a + b; // 14
b = a - b; // 5
a = a - b; // 9
printf("a=%d b=%d", a, b);
return 0;
}Output:
a=9 b=5
a=9 b=5
Summary
- Add then subtract to swap without a third variable.
- XOR (^) also works: a^=b; b^=a; a^=b;
तरकीब
💡 Note
आप बिना temporary variable के दो numbers swap कर सकते हैं arithmetic या XOR से।
Arithmetic से
C
#include <stdio.h>
int main() {
int a = 5, b = 9;
a = a + b; // 14
b = a - b; // 5
a = a - b; // 9
printf("a=%d b=%d", a, b);
return 0;
}Output:
a=9 b=5
a=9 b=5
सारांश
- Add फिर subtract करके बिना third variable swap करें।
- XOR (^) भी काम करता है: a^=b; b^=a; a^=b;