C Program to Swap Two Numbers (Using Third Variable / Without Third Variable)
Swapping means exchanging the values of two variables. This program demonstrates two methods to swap numbers — one using a temporary variable and another without using any third variable.
Concept Overview
In the first approach, a temporary variable is used to store one of the numbers temporarily. In the second method, arithmetic operations are used to swap values without a third variable.
Program 1: Using Third Variable
C
#include <stdio.h>
int main() {
int a, b, temp;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Before Swapping: a = %d, b = %d\n", a, b);
// Swap using a temporary variable
temp = a;
a = b;
b = temp;
printf("After Swapping: a = %d, b = %d\n", a, b);
return 0;
}
Sample Output (Using Third Variable)
Enter two numbers: 10 20 Before Swapping: a = 10, b = 20 After Swapping: a = 20, b = 10
Program 2: Without Using Third Variable
C
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Before Swapping: a = %d, b = %d\n", a, b);
// Swap without using a temporary variable
a = a + b;
b = a - b;
a = a - b;
printf("After Swapping: a = %d, b = %d\n", a, b);
return 0;
}
Sample Output (Without Third Variable)
Enter two numbers: 15 30 Before Swapping: a = 15, b = 30 After Swapping: a = 30, b = 15
Explanation
- Using Third Variable – A temporary variable stores one value while swapping.
- Without Third Variable – Swapping is done using arithmetic operations (`+` and `-`) or XOR logic.
- `printf()` – Displays values before and after swapping.
Note: Note: Be cautious when using arithmetic operations for swapping very large numbers, as it can cause integer overflow.
Codecrown