Q:

C Program to swap two numbers using ex-or operator:

belongs to collection: C Programming on Numbers

0

The bitwise XOR operator can be used to swap two variables. Here the concept is that EX-OR of two same numbers is zero. The XOR of two numbers a and b returns a number which has all the bits as 1 wherever bits of a and b differ.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <stdio.h>
int main()
{
    int a, b ;
    printf("Enter Value of a = ");
    scanf("%d", &a);
    printf("Enter Value of b = ");
    scanf("%d", &b);
    a = a ^ b; // a now becomes 30
    b = a ^ b; // b becomes 10
    a = a ^ b; // a becomes 20
    printf("After Swapping: a = %d, b = %d", a, b);
    return 0;
}

 

Output:

Enter Value of a = 10
Enter Value of b = 20

After Swapping: a = 20, b = 10

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C Programming on Numbers

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C Program to find given number is the sum of first... >>
<< C Program to reverse digits of a number...