C Program to Swap Two Numbers Using Temporary Variable
In this tutorial, we will learn how to swap two numbers in C programming using a temporary variable. This is one of the most common beginner-level programs in C.
Concept Overview
Swapping means exchanging the values of two variables. In this method, a third variable (temporary variable) is used to store one value while the exchange takes place.
Program
C
#include <stdio.h>
int main() {
int a, b, temp;
printf("Enter 2 numbers: ");
scanf("%d %d", &a, &b);
// Swapping using temporary variable
temp = a;
a = b;
b = temp;
printf("After swapping: %d %d\n", a, b);
return 0;
}
Output
Enter 2 numbers: 10 20 After swapping: 20 10
Explanation
- `int a, b, c;` – Declares three integer variables.
- `scanf("%d %d", &a, &b);` – Takes input from the user.
- `c = a;` – Stores the value of `a` in the temporary variable `c`.
- `a = b;` – Assigns the value of `b` to `a`.
- `b = c;` – Assigns the stored value from `c` to `b`.
- After these steps, the values of `a` and `b` are successfully swapped.
Codecrown