Swapping means to interchange the value of two variables.For example if variable a store 10 and another variable b store 20 then after swapping b contains 10 and a contains 20. In c we can do the swapping in two way :-
- using extra variable
- without using extra variable
Swapping of two numbers in C
Program 1:Using extra variable
#include<stdio.h>
void swap(int *a, int *b)
{
int temp; //extra variable
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int a, b;
printf("nEnter the first number : ");
scanf("%d", &a);
printf("nEnter the Second number : ");
scanf("%d", &b);
swap(&a, &b);
printf("nValues after swapping ");
printf("nFirst number : %d", a);
printf("nSecond number : %d", b);
return (0);
}
Program 2 : Without using extra variable.
#include <stdio.h>
int main()
{
int a, b;
printf("Enter two integers to swap\n");
scanf("%d%d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("a = %d\nb = %d\n",a,b);
return 0;
}
Program 2 : Using 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;
}
Program 4 :Using call by reference
#include <stdio.h>
void swap(int*, int*);
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *b;
*b = *a;
*a = temp;
}
Program 2 : Using bitwise XOR
#include <stdio.h>
int main()
{
int x, y;
printf("Enter two integers to swap\n");
scanf("%d%d", &x, &y);
printf("x = %d\ny = %d\n", x, y);
x = x ^ y;
y = x ^ y;
x = x ^ y;
printf("x = %d\ny = %d\n", x, y);
return 0;
}
Output