C Program to Swap Two Numbers - Using Temp, Arithmetic & XOR

Swap Using a Temporary Variable

#include <stdio.h>
int main() {
    int a = 5, b = 10, temp;
    temp = a;
    a = b;
    b = temp;
    printf("a = %d, b = %d\n", a, b);
    return 0;
}
a = 10, b = 5
        

Here the value of a is preserved in temp so that it can be assigned back to b after a receives b’s original value.

Swap Using Arithmetic Operations

#include <stdio.h>
int main() {
    int a = 5, b = 10;
    a = a + b;
    b = a - b;
    a = a - b;
    printf("a = %d, b = %d\n", a, b);
    return 0;
}
a = 10, b = 5
        

This method avoids a temporary variable by using arithmetic operations: after a is set to a + b, subtracting b from a yields the original a which can be stored in b, and subtracting the new b from a yields the original b.

Swap Using XOR

#include <stdio.h>
int main() {
    int a = 5, b = 10;
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    printf("a = %d, b = %d\n", a, b);
    return 0;
}
a = 10, b = 5
        

The XOR method leverages the property that applying XOR twice with the same operand retrieves the original value. After three XOR operations, the values of a and b are exchanged.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...