In this tutorial, we are going to learn How to swap two number using a bitwise operator in C language
For Examples,
Input : a = 30, b = 44 Output : a = 44, b = 30
Input: a = 500,b = 250 Output: a=250,b = 500
Input : a = 2000, b = 1000 Output : a = 1000, b = 2000
The logic used in this program is explained below:
Let’s try to understand how the bitwise operator(^) works with two numbers. Let’s assume we have two numbers a = 10 and b = 5
The binary equivalent of 10 is 1010 and 5 is 0101
Now below is the bitwaise (^) operation of these two binary numbers as follows:
a = 10 = 1010
b = 5 = 0101
————————–
1111
Swap two number using the bitwise operator in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <stdio.h> int main() { int a,b; // Taking first number from the user and storing in variable a printf("Enter the value of a :"); scanf("%d",&a); // Taking second number from the user and storing in variable b printf("Enter the value of b :"); scanf("%d",&b); printf("----------------------------------\n"); //Printing both numbers before swapping printf("Before swapping :a=%d , b=%d",a,b); //Logic to swap two numbers a=a^b; b=a^b; a=a^b; //Printing both numbers after swapping printf("\nAfter swapping :a=%d , b=%d",a,b); } |
The output of the above program:
Enter the value of a :10
Enter the value of b :20
———————————-
Before swapping :a=10 , b=20
After swapping :a=20 , b=10
In this post, we learnt about How to swap two number using the bitwise operator in C language
You May Also Like:
Swapping of two numbers in C Language by using a temporary variable
Thank you for visiting.
If you have any feedback or suggestion please drop in below the comment box.