Swap Variable Contents Using XOR Bit wise Operator

By | June 19, 2019

Swap Variable Contents Using XOR Bit wise Operator in a C program. This is a simple C program for exchanging values of two variables using XOR Bit wise operator ^. There is no need using a third variable for the above mentioned swapping.

 

/*
Write a C program to swap values of two 
variables usin XOR ^ bitwise operator
without using third variable
*/
#include<stdio.h>  
int main()   
{   
  int num1, num2, temp;  
  printf("Enter First Number and Second Number to Swap=");  
  scanf("%d %d",&num1,&num2);  
  printf("Before swapping : First Number = %d\n",num1);  
  printf("Second Number =%d\n",num2);  
/* now we swap values with a mathematical trick*/  
  num1 = num1 ^ num2;
  num2 = num1 ^ num2;
  num1 = num1 ^ num2;
  printf("After swapping: First Number =%d   Second Number = %d",num1,num2);   
  return 0;   
}  

Here is an image to show the sample run and output of swapping values of variables with the help of XOR bit wise operator in C Language.

Swap Variable Contents Using XOR Bit wise Operator in a C program. This is a simple C program for exchanging values of two variables using XOR Bit wise operator ^.

Swap Variable Contents Using XOR Bit wise Operator in a C program. This is a simple C program for exchanging values of two variables using XOR Bit wise operator ^.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *