C program to swap two numbers
C program to swap two numbers with and without using third variable, using pointers, functions (Call by reference) and using bit-wise XOR operator. Swapping means interchanging. If the program has two variables a and b where a = 4 and b = 5, after swapping them, a = 5, b = 4. In the first C program, we use a temporary variable to swap two numbers.
Swapping of two numbers in C
#include <stdio.h>
int main()
{
int x, y, t;
printf(“Enter two integers\n“);
scanf(“%d%d”, &x, &y);
printf(“Before Swapping\nFirst integer = %d\nSecond integer = %d\n“, x, y);
t = x;
x = y;
y = t;
printf(“After Swapping\nFirst integer = %d\nSecond integer = %d\n“, x, y);
return 0;
}
The output of the program:
Enter two integers
23
45
Before Swapping
First integer = 23
Second integer = 45
After Swapping
First integer = 45
Second integer = 23
Swapping of two numbers without third variable
You can also swap two numbers without using third variable. In this case C program will be as follows:
#include <stdio.h>
int main()
{
int a, b;
printf(“Input two integers (a & b) 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;
}
Output of program:
To understand the logic, choose the variables ‘a’ and ‘b’ as ‘7’ and ‘9’ respectively, and do according to the program. You can choose any other combination of numbers as well. Sometimes it’s an excellent way to understand a program.
Swap function in C language
In this method we will make a function to swap numbers. We will use call by reference.
#include <stdio.h>
void swap(int*, int*); //Swap function declaration
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;
}
//Swap function definition
void swap(int *a, int *b)
{
int t;
t = *b;
*b = *a;
*a = t;
}
Swap two numbers using pointers
#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;
}
C programming code to swap using bit-wise XOR
#include <stdio.h>
int main()
{
int x, y;
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;
}
Sorting algorithms use swapping to arrange numbers in either ascending order or descending order.