Summary: In this tutorial, we will learn different ways to swap two numbers without using the third variable in the C programming language.

Method 1: Using + and – Operator

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

Output:

Before Swap:
a: 5
b: 6
After Swap:
a: 6
b: 5


In this method, we have used plus (+) and minus (-) operator to swap the values of a and b without declaring the third variable.

We add both numbers and assign a new value for each variable by subtracting the value of the other correspondent from the sum.

Method 2: Using * and / Operator

#include <stdio.h>
 
int main()
{
    int a=4, b=3;
 
    printf("Before Swap: \n");
    printf("a: %d \n", a);
    printf("b: %d \n", b);
 
    a = a*b;
    b = a/b; // (a*b)/b == a
    a = a/b; // (a*b)/a == b
 
 
    printf("After Swap: \n");
    printf("a: %d \n", a);
    printf("b: %d \n", b);
 
    return 0;
}

Output:

Before Swap:
a: 4
b: 3
After Swap:
a: 3
b: 4


This method applies the same approach as the previous method to swap two numbers but is implemented using the multiplication (*) and division (/) operator.

We multiply both the numbers and assign a new value for each variable by dividing the value of the other correspondent from the product.

Method 3: Using XOR (^) Operator

#include <stdio.h>
 
int main()
{
    int a=12, b=9;
 
    printf("Before Swap: \n");
    printf("a: %d \n", a);
    printf("b: %d \n", b);
 
    a = a^b;
    b = a^b;
    a = a^b;
 
    printf("After Swap: \n");
    printf("a: %d \n", a);
    printf("b: %d \n", b);
 
    return 0;
}

Output:

Before Swap:
a: 12
b: 9
After Swap:
a: 9
b: 12


In this method, we store XOR’s hybrid value (i.e. a^b) in a and then we extract another correspondent value using the same expression,

i.e. Second Variable = (XOR Hybrid of Both) ^ (First Variable).

These were some of the ways we can swap two numbers without using any temporary variables in programming.

Leave a Reply