Swapping two numbers means exchanging the values of two variables. The simplest way to swap them is by using a temporary variable.
- First, store the value of the first variable in a temporary variable.
- Then, assign the second value to the first variable and the temporary value to the second variable.
Illustration
Input:
a = 5, b = 10
Output:
a = 10, b = 5
Methods to Swap Two Numbers in C
The following approaches can be used to swap two numbers:
1. Using a Temporary Variable
This is the simplest approach. Store the value of the first variable in a temporary variable, then exchange the values using the temporary variable.
#include <stdio.h>
int main() {
int a = 5, b = 10, temp;
// Swapping values of a and b
temp = a;
a = b;
b = temp;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output
a = 10, b = 5
Explanation
- temp stores the original value of a.
- The value of b is assigned to a, and the stored value in temp is assigned to b.
2. Without Using a Temporary Variable
Arithmetic operations can be used to swap two integers without an additional variable.
#include <stdio.h>
int main() {
int a = 5, b = 10;
// Arithmetic operations to swap values
a = a + b;
b = a - b;
a = a - b;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output
a = 10, b = 5
Explanation
- a first stores the sum of both values.
- Subtracting b from a gives the original value of a, and the final subtraction gives the original value of b.
Note: This method can cause integer overflow if a + b exceeds the range of int.
3. Using the Bitwise XOR Operator
For integer values, the XOR operator can swap two numbers without a temporary variable. XOR operations cancel matching bits and preserve the information needed to recover the original values.
#include <stdio.h>
int main() {
int a = 5, b = 10;
// Apply XOR operations in the given order
// to swap values
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output
a = 10, b = 5
Explanation
- The first XOR stores the combined bit information of a and b in a.
- The next two XOR operations recover the original values in reversed order.
Note: The XOR method is applicable to integer types and is generally less readable than using a temporary variable.