Introduction
Swapping two numbers means interchanging their values. In this lab, we will learn how to swap two numbers in C language using different methods such as using a temporary variable, addition and subtraction, bitwise operators, multiplication and division.
Note: You need to create the file
~/project/main.cyourself to practice coding and learn how to compile and run it using gcc.
cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main
Using a Temporary Variable
We can swap two numbers using a temporary variable by following these steps:
- Declare three variables
x,yandtemp. - Assign values to
xandy. - Store the value of
xintemp. - Assign the value of
ytox. - Assign the value of
temptoy. - Print the values of
xandy.
#include <stdio.h>
int main() {
int x = 5, y = 7, temp;
// Step 3
temp = x;
// Step 4 and 5
x = y;
y = temp;
// Step 6
printf("After swapping, x = %d and y = %d\n", x, y);
return 0;
}
Using Addition and Subtraction
We can swap two numbers using addition and subtraction by following these steps:
- Assign values to
xandy. - Add
xandyand assign the result tox. - Subtract the original value of
yfromxand assign toy. - Subtract the original value of
yfrom the new value ofxand assign tox. - Print the values of
xandy.
#include <stdio.h>
int main() {
int x = 5, y = 7;
// Step 2 and 3
x = x + y;
y = x - y;
// Step 4
x = x - y;
// Step 5
printf("After swapping, x = %d and y = %d\n", x, y);
return 0;
}
Using Bitwise Operators
We can swap two numbers using bitwise operators by following these steps:
- Assign values to
xandy. - XOR
xandyand assign the result tox. - XOR the new value of
xandyand assign the result toy. - XOR the new value of
xandyand assign the result tox. - Print the values of
xandy.
#include <stdio.h>
int main() {
int x = 5, y = 7;
// Step 2 and 3
x = x ^ y;
y = x ^ y;
// Step 4
x = x ^ y;
// Step 5
printf("After swapping, x = %d and y = %d\n", x, y);
return 0;
}
Using Multiplication and Division
We can swap two numbers using multiplication and division by following these steps:
- Assign values to
xandy. - Multiply
xandyand assign the result tox. - Divide the new value of
xbyyand assign the result toy. - Divide the new value of
xby the new value ofyand assign the result tox. - Print the values of
xandy.
#include <stdio.h>
int main() {
int x = 5, y = 7;
// Step 2 and 3
x = x * y;
y = x / y;
// Step 4
x = x / y;
// Step 5
printf("After swapping, x = %d and y = %d\n", x, y);
return 0;
}
Summary
In this lab, we learned how to swap two numbers using four different methods: using a temporary variable, addition and subtraction, bitwise operators and multiplication and division. Swapping two numbers is useful in programming when we want to change the order of two values or perform operations that require switching the values of two variables.



