C Program to swap two numbers using bit wise XOR operation

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

What are bitwise operators in C?

In this C program, we use a Bitwise XOR operator to swap the numbers. Before starting, we need to know about the Bitwise operators. Bitwise operators works at the byte level, the basic unit of a memory that is addressable. The leading bitwise operators are Bitwise AND, OR, and NOT operators. Here we are using bitwise XOR, which is called Exclusive OR. XOR takes two inputs and returns one if any of the input is one. If both inputs are One or Zero, it returns a Zero.

How bitwise operators help to swap the numbers?

Let the 'x' be 10 and 'y' be 5 so in Binary 'x' (1010) and 'y' (0101) then we use 'x = x ^ y' and 'x' now becomes 15 (1111). now we apply y = x ^ y, then 'y' becomes 10 (1010). Finally, we apply x = x ^ y to make 'x' becomes 5 (0101). The result of Bitwise XOR Operator is one if corresponding bits of two Operands are opposite. The result of the XOR operator is 0 if the corresponding bits of two operands are the same. Let's take a simple example to understand more about this.

10 - 1010 (in binary)

13 - 1101 (in binary)

Then the XOR operation of 12 and 25 is 0111 0111 - 7 (in decimal).

The logic of this program is first to Declare two variables 'i' and j'.Then accept the Integer numbers from the user and display them. Then Swap the Numbers using XOR Operator. Then display the numbers using the printf function.


STEP 1: Include the header files to use the built-in functions in the C program.

STEP 2: Declare the variables 'i, k as an integer.

STEP 3: Read two integers from the user and store them into the variables 'i' and 'k'.

STEP 4: Display the integers as the number before Swapping using the printf function.

STEP 5: Swap the numbers like 'i = i^k', 'k = i^k', and 'i= i^k'.

STEP 6: Display, After Swapping the numbers are 'i' and 'k'.

C Source Code

                                          #include <stdio.h>

void main() {
  long i, k;
  printf("Enter two integers\n");
  scanf("%ld %ld", & i, & k);
  printf("\nBefore swapping i= %ld and k = %ld", i, k);
  i = i ^ k; /* swap the numbers as we discussed in the logic part */
  k = i ^ k;
  i = i ^ k;
  printf("\nAfter swapping i= %ld and k = %ld", i, k); /* prints the swapped numbers */


Enter two integers
Before swapping i= 12 and k = 13
After swapping i= 13 and k = 12