Write a C program to input any two numbers from user and swap values of both numbers using bitwise operator. How to swap two number using bitwise operator in C programming. Logic to swap two numbers using bitwise operator in C programming.
Example
Input
Input first number: 22 Input second number: 65
Output
First number after swapping: 65 Second number after swapping: 22
Required knowledge
Bitwise operators, Data types, Basic input/output
Logic to swap two numbers using bitwise operator
There are tons of discussions going around the internet to swap two numbers without using temporary variable (third variable). We can use bitwise XOR ^
operator to swap to numbers. Bitwise XOR operator evaluates each bit of the result to 1 if corresponding bits of the operands are different otherwise evaluates 0.
Suppose two integer values a and b
Perform, x = a ^ b
Now x ^ b
will evaluate to a
and x ^ a
will evaluate to b.
Program to swap two numbers
/**
* C program to swap two numbers using bitwise operator
*/
#include <stdio.h>
int main()
{
int num1, num2;
/* Input two numbers from user */
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);
printf("Original value of num1 = %d\n", num1);
printf("Original value of num2 = %d\n", num2);
/* Swap two numbers */
num1 ^= num2;
num2 ^= num1;
num1 ^= num2;
printf("Num1 after swapping = %d\n", num1);
printf("Num2 after swapping = %d\n", num2);
return 0;
}
Output
Enter any two numbers: 22 65 Original value of num1 = 22 Original value of num2 = 65 Num1 after swapping = 65 Num2 after swapping = 22
Happy coding 😉
Recommended posts
- Bitwise operator programming exercises index.
- C program to find one’s complement of a binary number.
- C program to find two’s complement of a binary number.
- C program to total number of zeros and ones in a binary number.
- C program to convert decimal to binary number system using bitwise operator.
- C program to check whether a number is even or odd using bitwise operator.