Beginner Logical Thinking C

Swap Two Numbers Without a Third Variable in C

Exchange the values of two integer variables in C without using a temporary variable.

  • TimeO(1)
  • SpaceO(1)
  • Hints3
  • Read3 min
Quick answer

To swap a and b without a third variable in C, use three steps: a = a + b; b = a - b; a = a - b;. After them, a holds the old b and b holds the old a. The XOR version a ^= b; b ^= a; a ^= b; also works and cannot overflow. In real code a temporary variable is clearer, but this question is common in labs and vivas because it tests how well you understand operators.

Arithmetic operatorsBitwise XORPointersInteger overflow
1

Problem statement

Write a C program to swap two numbers without a third variable. Given a = 10 and b = 20, after the swap a should be 20 and b should be 10.

Do not declare a temp variable. Use arithmetic or bitwise operators.

Input

Two integers a and b.

Output

The values of a and b before and after the swap.

Examples

Example 1
Inputa = 10, b = 20
Outputa = 20, b = 10

a becomes 30, then b becomes 30 - 20 = 10, then a becomes 30 - 10 = 20.

Example 2
Inputa = 5, b = 9 (XOR method)
Outputa = 9, b = 5

XOR-ing twice with the same value gives back the original.

Constraints

  • For the + and - method, a + b must fit in an int
  • For the * and / method, neither value can be 0 and a * b must fit in an int
2

Think before you code

Reveal the questions to ask yourself first
  • If a holds the sum of both numbers, how can you get the old a back?
  • Which variable should you change first?
  • What could go wrong if a + b is very large?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Store the sum in a first: a = a + b.
2 Hint 2
Now a - b gives the old a. Put it in b.
3 Hint 3
Now a - b (with the new b) gives the old b. Put it in a.
4

Approach

Reveal the step-by-step approach

Method 1: addition and subtraction

a = a + b;   /* a holds the sum */
b = a - b;   /* sum - old b = old a */
a = a - b;   /* sum - old a = old b */

Method 2: XOR

x ^ x = 0 and x ^ 0 = x. So (a ^ b) ^ b gives back a.

a = a ^ b;
b = a ^ b;   /* (a ^ b) ^ b = old a */
a = a ^ b;   /* (a ^ b) ^ old a = old b */

Method 3: multiplication and division

a = a * b; b = a / b; a = a / b; works only when neither number is 0 and the product fits in an int.

Method Works with 0? Overflow risk Works for float?
+ and - Yes Yes, if a + b is too big Yes, with rounding error
XOR Yes No No, XOR needs integers
* and / No Yes, and larger Yes, with rounding error
temp variable Yes No Yes
5

Dry run

Walk through the example step by step

Addition method, a = 10, b = 20:

step         | a  | b
-------------+----+----
start        | 10 | 20
a = a + b    | 30 | 20
b = a - b    | 30 | 10
a = a - b    | 20 | 10

XOR method, a = 5 (0101), b = 9 (1001):

step         | a          | b
-------------+------------+-----------
start        | 0101 (5)   | 1001 (9)
a = a ^ b    | 1100 (12)  | 1001 (9)
b = a ^ b    | 1100 (12)  | 0101 (5)
a = a ^ b    | 1001 (9)   | 0101 (5)
6

Solution

Reveal the full C solution
solution.c
#include <stdio.h>

int main(void) {
    int a = 10, b = 20;
    printf("Before swap: a = %d, b = %d\n", a, b);

    a = a + b;   /* a = 30 */
    b = a - b;   /* b = 30 - 20 = 10 */
    a = a - b;   /* a = 30 - 10 = 20 */

    printf("After swap:  a = %d, b = %d\n", a, b);
    return 0;
}

Output:

Before swap: a = 10, b = 20
After swap:  a = 20, b = 10

Swap two numbers using XOR in C, and the * / method

#include <stdio.h>

int main(void) {
    int a = 5, b = 9;
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    printf("a = %d, b = %d\n", a, b);

    int x = 4, y = 7;
    x = x * y;   /* 28 */
    y = x / y;   /* 4 */
    x = x / y;   /* 7 */
    printf("x = %d, y = %d\n", x, y);
    return 0;
}
a = 9, b = 5
x = 7, y = 4

Swap with user input and a function

To swap the caller's variables, a function needs their addresses. Passing plain ints would only swap copies.

#include <stdio.h>

void swap(int *p, int *q) {
    if (p == q) {
        return;
    }
    *p = *p + *q;
    *q = *p - *q;
    *p = *p - *q;
}

int main(void) {
    int a, b;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);
    swap(&a, &b);
    printf("After swap: a = %d, b = %d\n", a, b);
    return 0;
}
Enter two numbers: 15 -4
After swap: a = -4, b = 15

The p == q check matters. If both pointers point to the same variable, the first line doubles it and the second line sets it to 0, so the value is lost. The XOR version has the same problem.

Why is this asked in vivas?

It checks three things in one short question: that you understand how assignment changes a variable step by step, that you know operators beyond +, and that you can spot limits such as overflow and the zero case. Be ready to say that in real programs a temp variable is clearer and just as fast with modern compilers.

The Java version is on swap two numbers without a third variable. More lab programs are in C programs for beginners, and pointer basics are in what is a pointer in C.

TimeO(1)
SpaceO(1)
7

Review before the interview

Common mistakes

  • Writing b = a - b before a = a + b. The order of the three lines is fixed.
  • Using the * and / method when one value is 0, which divides by zero.
  • Writing a swap function that takes int a, int b. It swaps copies, and main sees no change.
  • Writing it in one line as a = a + b - (b = a). This mixes a read and a write of b without a sequence point, which is undefined behaviour in C.

Edge cases to test

  • Equal values: a = b = 7 still works with + and - and with XOR.
  • Negative numbers work with + and - and with XOR.
  • Large values: 2000000000 + 2000000000 overflows a 32-bit int, which is undefined behaviour for signed ints. XOR has no such risk.
  • Same variable through pointers: swap(&a, &a) sets a to 0 without the p == q check.

Interview follow-ups

  • Why does XOR swapping fail when both pointers point to the same variable?
  • How would you swap two numbers in one line in Python?
  • Can you swap two strings without a third variable?

Keep practising

Building your programming basics?

CodeBegun’s programs build problem-solving with mentor review and mock interviews, online or in Madhapur, Hyderabad.

Chat with us