C PROGRAMMING PROGRAM • OPERATORS & CONVERSIONS

Swap Two Numbers Without a Temporary Variable

Learn how to swap two numbers without a temporary variable using a clear C program.

BeginnerArithmetic assignmentSwapVariables

PROBLEM UNDERSTANDING

Input and expected output

Sample input
10 25
Sample output
After swapping: 25 10

COMPLETE C PROGRAM

Complete C implementation

swap-without-temporary-variable.c
Open in compiler
#include <stdio.h>

int main(void)
{
    long long first, second;

    printf("Enter two integers: ");
    scanf("%lld %lld", &first, &second);
    first = first + second;
    second = first - second;
    first = first - second;
    printf("After swapping: %lld %lld\n", first, second);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

After swapping: 25 10
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Store the combined value temporarily in one variable and recover both values by subtraction.
  3. Display the computed result.

Store the combined value temporarily in one variable and recover both values by subtraction.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Arithmetic swapping may overflow for very large integers.

Check this

Do not change the order of the three assignments.

Check this

Prefer a temporary variable in production code for clarity.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.