In this article, you will learn to swap two numbers in C programming.
Examples :
Input : x = 10, y = 20; Output : x = 20, y = 10 Input : x = 50, y = 100 Output : x = 100, y = 100
Algorithm :
- Assign x to a temp variable, i.e., temp = x
- Assign y to x, i.e., x = y
- Assign temp to y, i.e., y = temp
1. With using a Temporary Variable :
// C program to swap two variables
#include <stdio.h>
int main()
{
// take input
int x =10, y=20;
printf("Before swap : %d %d\n", x, y);
// swap using temporary variable
int temp = x;
x = y;
y = temp;
printf("After swap : %d %d\n", x, y);
// successful completion
return 0;
}
Output :
Before swap : 10 20 After swap : 20 10
2. Without Using Temporary Variable :
// C program to swap two variables
#include <stdio.h>
int main()
{
// take input
int x =10, y=20;
printf("Before swap : %d %d\n", x, y);
x = x -y;
y = x + y;
x = y -x;
printf("After swap : %d %d\n", x, y);
// successful completion
return 0;
}
Output :
Before swap : 10 20 After swap : 20 10
3. Using Bitwise operator :
// C program to swap two variables
#include <stdio.h>
int main()
{
// take input
int x =10, y=20;
printf("Before swap : %d %d\n", x, y);
x = x^y;
y = x^y;
x = x^y;
printf("After swap : %d %d\n", x, y);
// successful completion
return 0;
}
Output :
Before swap : 10 20 After swap : 20 10
4. Using Multiplication and Division :
// C program to swap two variables
#include <stdio.h>
int main()
{
// take input
int x =10, y=20;
printf("Before swap : %d %d\n", x, y);
x = x*y;
y = x/y;
x = x/y;
printf("After swap : %d %d\n", x, y);
// successful completion
return 0;
}
Output :
Before swap : 10 20 After swap : 20 10
Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.
