C Swap Two Numbers Program

Beginner
5 min read
Updated: Oct 2026
3 programs
Live preview

What Does Swap Two Numbers Mean?

To swap two numbers means exchange their values: after the swap, the first variable holds what the second had, and the second holds what the first had.

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

Default interview answer:
  temp = a
  a = b
  b = temp
MethodIdeaNotes
Temp variableSave, overwrite, restoreClearest and safest
Arithmetica+b, then subtractCan overflow int
XORThree ^= stepsIntegers only; interview trick

How to Swap Two Numbers in C

Four clear steps for the temp method — then optional no-temp variants.

  1. Store the first value in temp.
  2. Copy the second value into the first variable.
  3. Copy temp into the second variable.
  4. Or, if asked, show arithmetic / XOR as alternatives (mention overflow and readability).
MethodIdeaTimeBest for
Temp variabletemp = a; a = b; b = temp;O(1)Interviews, real code
ArithmeticEncode both in a sum, then peelO(1)No-temp follow-up
XORa ^= b three timesO(1)Integer bit trick

Pseudocode

Pseudocode
function SwapTemp(a, b):
    temp = a
    a = b
    b = temp
    return a, b

function SwapArithmetic(a, b):
    a = a + b
    b = a - b
    a = a - b
    return a, b

function SwapXor(a, b):
    if a != b:
        a = a XOR b
        b = b XOR a
        a = a XOR b
    return a, b

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
DefaultUse a temporary variable
Temp stepstemp = a; a = b; b = temp;
Equal valuesSwap still works; result unchanged
Arithmetic riska + b may overflow int
PointersA function swap needs pointers: swap(&a, &b)
Classic check5, 10 → 10, 5

Live Preview

Enter two integers and swap them with the temporary-variable method.

Whole numbers only. Tap a chip or type a pair.

Result
Before: a = 5, b = 10
temp = 5
a = 10
b = 5
After:  a = 10, b = 5

Worked Walkthrough — a = 5, b = 10

Trace the temporary-variable swap step by step.

Calculation
Start:  a = 5, b = 10

Step 1: temp = a      → temp = 5
Step 2: a = b         → a = 10
Step 3: b = temp      → b = 5

Result: a = 10, b = 5

C Programs

Start with a temporary variable — the interview default. Then show arithmetic and XOR as no-temp alternatives.

Example 1 — Swap Using Temp Variable

Save the first value, overwrite it, then restore into the second variable.

C
#include <stdio.h>

int main(void)
{
    int num1 = 5;
    int num2 = 10;
    int temp;

    printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);

    temp = num1;
    num1 = num2;
    num2 = temp;

    printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);
    return 0;
}

How It Works

  1. temp = num1 saves 5 so it is not lost.
  2. num1 = num2 copies 10 into the first variable.
  3. num2 = temp restores the saved 5.
  4. Works for equals, negatives, and any assignable type.
  5. This is the answer to give first in interviews.

Example 2 — Swap Using Arithmetic

No named temp — the sum holds both values, then subtraction peels them apart.

C
#include <stdio.h>

int main(void)
{
    int num1 = 5;
    int num2 = 10;

    printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);

    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;

    printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);
    return 0;
}

How It Works

  1. num1 = num1 + num2 stores 15 (both originals combined).
  2. num2 = num1 - num2 becomes 15 - 10 = 5 (old num1).
  3. num1 = num1 - num2 becomes 15 - 5 = 10 (old num2).
  4. Near INT_MAX, a + b can overflow — prefer temp in real code.
  5. Good follow-up when asked to swap without a temporary variable.

Example 3 — Swap Without Temp (XOR Trick)

Three XOR steps trade bit patterns. Keep it as an interview curiosity.

C
#include <stdio.h>

int main(void)
{
    int a = 5;
    int b = 10;

    if (a != b)
    {
        a ^= b;
        b ^= a;
        a ^= b;
    }

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

How It Works

  1. a ^= b mixes both bit patterns into a.
  2. b ^= a recovers the original a into b.
  3. a ^= b recovers the original b into a.
  4. The a != b guard is a safe habit when mentioning aliasing edge cases.
  5. Prefer temp for readability; mention XOR only if asked.

Edge Cases & Pitfalls

Check these before calling the solution done.

Equal

Same values

Swap still runs; both variables keep the same number.

Overflow

Arithmetic risk

a + b can overflow int. Prefer a temp variable for large values.

XOR

Integers only

Bitwise XOR is not for floats. Temp works more broadly.

Readability

Temp first

In interviews and production, lead with temp. Treat XOR as optional.

Time and Space Complexity

ProgramTimeExtra space
Temp variableO(1)O(1)
ArithmeticO(1)O(1)
XORO(1)O(1)

A swap touches a fixed number of variables — constant time and space.

Key Takeaways

  • Goal: exchange the values stored in two variables.
  • Default: temp = a; a = b; b = temp;
  • No-temp options: arithmetic or XOR — mention overflow and readability.
  • Test set: (5,10) → (10,5); (4,4) stays; negatives work with temp.

One line: save one value, overwrite it, then put the saved value into the other variable.

Frequently Asked Questions

After a swap, the first variable holds the old second value, and the second holds the old first value.
Not always. Arithmetic or XOR can swap without a named temp, but a temporary variable is the clearest and safest default.
Swap still works; both values remain the same.
Yes. Temp and arithmetic work for any ints. XOR also works for integers.
All common swap methods are O(1) time and O(1) extra space.

Next: Triangular Number

Check whether a number sits in the sequence 1, 3, 6, 10, …

Triangular number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful