C PROGRAM • VARIABLES & ASSIGNMENT
Swap Two Numbers Using a Temporary Variable
Preserve the first value in temporary storage before exchanging two integers.
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
#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;
}CURRENT STEP
VARIABLES
| Scope | Name | Value |
|---|---|---|
| Not started | ||
CALL STACK
main()
PROGRAM OUTPUT
Waiting to run…
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read first and second.
- Copy first into temp.
- Copy second into first.
- Copy temp into second.
- 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.
