C PROGRAM • VARIABLES & ASSIGNMENT

Swap Two Numbers Using a Temporary Variable

Preserve the first value in temporary storage before exchanging two integers.

BeginnerAssignmentTemporary variableInput

PROBLEM UNDERSTANDING

Input and expected output

Sample input
10 25
Sample output
Enter two integers: 10 25
After swapping: 25 10

C PROGRAM

Complete program

swap-two-numbers.c
#include <stdio.h>

int main(void)
{
    int first, second, temp;
    printf("Enter two integers: " );
    scanf("%d %d", &first, &second);
    temp = first;
    first = second;
    second = temp;
    printf("After swapping: %d %d\n", first, second);
    return 0;
}

INTERACTIVE LEARNING

Debug this program line by line

Watch the active line, variables and output.

CURRENT STEP

Select Start to trace this program.

VARIABLES

ScopeNameValue
Not started

CALL STACK

main()

PROGRAM OUTPUT

Waiting to run…
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read first and second.
  2. Copy first into temp.
  3. Copy second into first.
  4. Copy temp into second.
  5. Print the exchanged values.

The temporary variable protects the original first value. Without temp, assigning second to first would destroy the value needed for the final assignment.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Assigning first = second before saving first.

Check this

Printing the original variables before performing all three assignments.