Tuesday, 19 March 2019

C program to swap two numbers using bit-wise XOR (method 3)

Swapping is used in sorting algorithms like in bubble sort,that is when we wish to arrange numbers in a particular order either in ascending order or in descending order.
Problem:
Given two numbers num1=a and num2=b, task is exchange values of these numbers i.e num1=b and num2=a;

Method 3: Using bit-wise XOR
#include<stdio.h>
int main(){
    int num1=10,num2=20;
    void swapXOR(int,int);  //function prototype
   printf("Values before swapping by call by value:num1=%d,num2=%d.\n",num1,num2);
    swapXOR (num1,num2);    
    return 0;
}
//function definition : using bitwise XOR operator
void swapXOR (int n1,int n2){
  n1 = n1 ^ n2;
  n2 = n1 ^ n2;
  n1 = n1 ^ n2;
  printf("Inside swap3 : num1=%d,num2=%d\n",n1,n2);
}
Output:
Please comment if you find anything incorrect, or you want to improve the topic discussed above.

No comments:

Post a Comment