Write a program to swap two integers using bitwise operators.

28 Dec 2022 Balmiki Mandal 0 C Programming

Swapping Integers Using Bitwise Operators in C Program

The C program to swap two integers using bitwise operators is a program that uses bitwise operators (such as bitwise AND, bitwise OR, and bitwise XOR) to exchange the values of two integers without using a temporary variable.

The program works by performing bitwise operations on the two numbers in order to swap their values. The XOR bitwise operator is particularly useful for this purpose, as it can be used to toggle the bits of a number.

#include <stdio.h>

int main() {
    int a, b;

    printf("Enter the value of a: ");
    scanf("%d", &a);

    printf("Enter the value of b: ");
    scanf("%d", &b);

    printf("Before swapping, a = %d and b = %d\n", a, b);

    // swapping using bitwise operators
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;

    printf("After swapping, a = %d and b = %d\n", a, b);

    return 0;
}

In this program, we first take two integer inputs a and b from the user. Then, we print the values of a and b before swapping.

After that, we swap the values of a and b using bitwise operators. The bitwise XOR operator (^) is used to perform the swap operation.

Finally, we print the values of a and b after swapping.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.