C Program to Swap Two Variables Using X-OR Operation

C program to swap two variables using X-OR operation can be designed by using bit-wise x-or operator (^). Swapping of two numbers means the exchanging of values between them. The algorithm, pseudocode and time complexity have been shown below.





1. Algorithm for swapping two variables using X-OR


1. Take two integers say $x,~y$ as input.

2. Compute $x= x~xor~y$

3. Compute $y= x~xor~y$

4. Compute $x= x~xor~y$

5. Return $x, y$




2. Pseudocode for swapping two variables using X-OR


Input : Two integer numbers $x,~y$

Output : $x,~y$ with exchanged values

1. Procedure swap($x, y$):

2. $x \leftarrow x~xor~y$

3. $y \leftarrow x~xor~y$

4. $x \leftarrow x~xor~y$

5. Return $x,~y$

6. End Procedure





3. Time complexity for swapping two variables using X-OR


Time Complexity: O(1)





4. C Program & output for swapping two variables using X-OR

Code has been copied
/********************************************
            alphabetacoder.com
C program to swap two numbers without third
variable but using bit-wise X-OR operator
*********************************************/
#include <stdio.h>

int main() {
    int num1, num2;
    // take input of two numbers 
    printf("Enter two numbers = ");
    scanf("%d%d", & num1, & num2);
    printf("Before swapping: number1 = %d and number2 = %d\n", num1, num2);

    //do swapping using X-OR (^)
    num1 = num1 ^ num2;
    num2 = num1 ^ num2;
    num1 = num1 ^ num2;

    printf("After swapping: number1 = %d and number2 = %d", num1, num2);
    return 0;
}

Output


Enter two numbers = 5 2

Before swapping: number1 = 5 and number2 = 2

After swapping: number1 = 2 and number2 = 5