📘 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

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

सारांश

  • Add फिर subtract करके बिना third variable swap करें।
  • XOR (^) भी काम करता है: a^=b; b^=a; a^=b;
← Back to C Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n