5 Ways to Swap Numbers In C Programming
There are various methods to swap two numbers. Here we are going to discuss some of the methods.
- Swapping of two numbers using a third/temp variable.
- Swapping of two numbers without using third/temp variable.
- Swapping of two numbers using bit-wise XOR operator.
- Swapping of two numbers using pointer.
- Swapping of two numbers using function.
1. Swapping of two numbers using a third/temp variable.
To swap two numbers using the third variable we have to declare a temp variable.
temp=x; //contains of x will be assigned to temp
Again y value we will assign to x .x value will be replaced with the y value.
x=y;
Now temp value we will assign to y.
y=temp;
Program :
#include<stdio.h>
int main() {
double first, second, temp;
printf("Enter first number: ");
scanf("%lf", &first);
printf("Enter second number: ");
scanf("%lf", &second);
// value of first is assigned to temp
temp = first;
// value of second is assigned to first
first = second;
// value of temp (initial value of first) is assigned to second
second = temp;
// %.2lf displays number up to 2 decimal points
printf("\nAfter swapping, first number = %.2lf\n", first);
printf("After swapping, second number = %.2lf", second); return 0;
}
2. Swapping of two numbers without using a third/temp variable.
Swapping can be done also without using a third variable.
x=x+y;//This will modify x=30 & y=20
y=x-y;//This will modify y value i.e y=10 & x=30
x=x-y;//This will modify x value i.e x=20 & y=10
Program :
#include <stdio.h>
int main()
{
int a, b;printf("Enter the first number: ");
scanf("%d", &a);printf("Enter the second number: ");
scanf("%d", &b);a = a - b;
b = a + b;
a = b - a;printf("After swapping, a = %d\n", a);
printf("After swapping, b = %d\n", b);return 0;}
3 .Swapping of two numbers using bit-wise XOR operator
Program :
#include <stdio.h>
int main()
{
int num1, num2;printf("\nEnter First Number : ");
scanf("%d", &num1);printf("\nEnter Second Number : ");
scanf("%d", &num2);num1 = num1 ^ num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;printf("\n Numbers after Exchange : ");
printf("\n Num1 = %d\n and\n Num2 = %d\n", num1, num2);return (0);}
4 . Swapping of two numbers using a pointer.
#include <stdio.h>int main()
int x, y, *a, *b, temp;printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);printf("Before Swapping\nx = %d\ny = %d\n", x, y);a = &x;
b = &y;temp = *b;
*b = *a;
*a = temp;printf("After Swapping\nx = %d\ny = %d\n", x, y);return 0;
}
5 . Swapping of two numbers using function
#include <stdio.h>void swap(int, int);int main(){
int a, b;printf("Enter values for a and b\n");
scanf("%d%d", &a, &b);printf("\n\nBefore swapping: a = %d and b = %d\n", a, b);
swap(a, b);
return 0;
}void swap(int x, int y){
int temp;temp = x;
x = y;
y = temp;printf("\nAfter swapping: a = %d and b = %d\n", x, y);}