Swapping of two numbers in C Language is the process in which the value of two variables is exchanged using some code. For example,
a = 5, b = 4
// After swapping:
a = 4, b = 5
We can swap two numbers in various ways as follows:
Swapping two variable values using a Temporary Variable
Swapping two variable values using Addition and Subtraction
Swapping two variable values using Bitwise Operator
Swapping two variable values using Multiplication and Division
Let's start with the algorithm steps first,
x
, y
and temp
x
and y
, say x = 5 and y = 7x
to temp
, say 5y
in x
, so y = 7 and x = 7temp
in y
, so temp = 5 and y = 5Below is a program to swap two numbers using temporary variable.
#include<stdio.h>
#include<conio.h>
void main()
{
int x = 10, y = 15, temp;
temp = x;
x = y;
y = temp;
printf("x = %d and y = %d", x, y);
getch();
}
x = 15 and y = 10
Let's start with the algorithm steps first,
Below is a program to swap two numbers without using any temporary variable, and use addition and subtraction operator for doing it.
#include<stdio.h>
#include<conio.h>
void main()
{
int x = 10, y = 15;
x = x + y - (y = x);
printf("x = %d and y = %d",x,y);
getch();
}
x = 15 and y = 10
XOR gives output as 1 when two different bits are XORed and give 0 when two same bits are XORed. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ. For example, XOR of 7 (0111) and 5 (0101) is (0010).
Below is the program to swap two numbers using bitwise operator.
#include<stdio.h>
#include<conio.h>
void main()
{
int x = 6, y = 4;
x = x^y;
y = x^y;
x = x^y;
printf("x = %d and y = %d", x, y);
getch();
}
x = 4 and y = 6
Let's start with the algorithm steps first,
Below is the program to swap two numbers using multiplication and division.
#include<stdio.h>
#include<conio.h>
void main()
{
int x = 6, y = 4;
x = x*y;
y = x/y;
x = x/y;
printf("x = %d and y = %d", x, y);
getch();
}
x = 4 and y = 6