C Program to Swap the values of two variables using Bit Manipulation


 

// Program by Akash Tripathi (@proakash256) 
 
// In this method :
// We will use XOR(^) Operator.

// Example : Let a = 5(101) and b = 7(111)

// Step 1 : a = a ^ b;
// So, a = 2 (010)

// Step 2 : b = a ^ b;
// So, b = 5 (101)

// Step 3 : a = a ^ b;
// So, a = 7 (111)

// Hence, the values got swapped.

#include <stdio.h>
int main()
{
    int a , b;
    printf("Enter the value of variable a : ");
    scanf("%d" , &a);
    printf("\nEnter the value of variable : ");
    scanf("%d" , &b);
    printf("\nNow , after swapping ,
            using third variable , \n");
    
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    
    printf("\nThe value of variable a : %d\n" , a);
    printf("The value of variable b : %d\n" , b);
    printf("\n");
    return 0;

Comments