C program to swap two numbers using bitwise operator

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.

Input first number: 22
Input second number: 65
Output first number after swapping: 65
Output second number after swapping: 22

Required knowledge:

Basic C programming, Bitwise operator


There are tons of discussions going around the internet about swapping two numbers without using a temporary variable (third variable). Swapping two numbers through bitwise XOR ^ operator is a solution to the problem mentioned above. We know that bitwise XOR operator evaluates each bit of the result to 1 if each corresponding bits of the two operands differ else evaluates to 0. Apart from this property bitwise operator also has an special property which can be explained through an example:
Let's suppose two integer values a and b
And let's suppose x = a ^ b
Then again x ^ b will evaluate to a and x ^ a will evaluate to b.
Properties of bitwise XOR operator

We are going to use this property of bitwise XOR operator to swap two numbers without using third variable.


 * C program to swap two numbers using bitwise operator

#include <stdio.h>

int main()
    int num1, num2;

    //Reads 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);

    num1 ^= num2;
    num2 ^= num1;
    num1 ^= num2;

    printf("Num1 after swapping = %d\n", num1);
    printf("Num2 after swapping = %d\n", num2);

    return 0;

Enter any two numbers: 22
Original value of num1 = 22
Original value of num2 = 65
Num1 after swapping = 65
Num2 after swapping = 22

Happy coding ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment