Written: August 14, 2026 · Updated: August 15, 2026
Swapping two numbers is one of the first logic drills in C: you move values between variables without losing either one.
This walkthrough keeps the logic small and readable so you can type it, run it, and then change one input at a time to see what happens.
What you will build
You will read two integers, store one in a temporary variable, then reassign so the values trade places before printing.
- Declare three integers: a, b, and temp
- Read a and b from the user
- Copy a into temp, copy b into a, copy temp into b
- Print the swapped values
Working C example
include <stdio.h>
int main(void) {
int a, b, temp;
printf("Enter two integers: ");
if (scanf("%d %d", &a, &b) != 2) {
return 1;
}
temp = a;
a = b;
b = temp;
printf("After interchange: %d %d\n", a, b);
return 0;
}
How the logic works
Read the program top to bottom: includes and main first, then the statements that change variables, then the print that proves the result.
If your output looks wrong, print the variables before and after the critical lines. That single habit catches most beginner bugs faster than rewriting the whole file.
Once the temp-variable version is clear, try the arithmetic or XOR variants for practice—but prefer the temp approach in real code for readability.
Keep learning
If this walkthrough on C Program to Interchange Two Numbers helped, open the code again and change one input or assumption. Small experiments beat rereading the same example.
Want more step-by-step tutorials like this? Browse blog.xqa.io — and tell us which topic you want next.