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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
10 25
Sample output
After swapping: 25 10
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
After swapping: 25 10
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Store the combined value temporarily in one variable and recover both values by subtraction.
- 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.
