Swap Two Numbers Without Using a Third Variable in C

This program shows how to swap the values of two variables without using a temporary (third) variable, using arithmetic operators.

C Program

#include <stdio.h>

int main() {
    int a, b;

    printf("Enter value of a: ");
    scanf("%d", &a);
    printf("Enter value of b: ");
    scanf("%d", &b);

    printf("\nBefore 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;
}

Explanation

  • a = a + b stores the sum of both numbers in a.
  • b = a - b subtracts the original b from the sum, leaving the original value of a in b.
  • a = a - b subtracts the new b (which is the original a) from the sum, leaving the original value of b in a.

No extra memory is used for a temporary variable — the swap happens purely through arithmetic. (An alternative approach uses the XOR bitwise operator instead of addition/subtraction.)

Sample Output

Enter value of a: 5
Enter value of b: 10

Before swapping: a = 5, b = 10
After swapping:  a = 10, b = 5

Leave a Comment