C Program to Swap Two Numbers Using XORing Operator


Bit-wise operators give a very tremendous way of working on bit. And the program that needs numbers of statements, and simply done on the single line using bit-wise operator.One of the bit-wise operator, The XORing operator (^) provides a way of swapping the values of two variables easily.

Lets see the Program ►►

#include<stdio.h>

#include<conio.h>

void main()

{

int a,b;

printf(“Enter the Values of A and B\n”);

scanf(“%d %d”,&a,&b);

a=a^b;

b=a^b;

a=a^b;

printf(“After Swapping \n a=%d \t b=%d”,a,b);

getch();

}

That’s It !!

The swapping of variables can be achieve by many ways as using the third variable and through the fashion of pointers (By Passing the Addresses). Swapping of variables through pointer is the best achieving way as we can easily keep track of the program and can access the variables easily anywhere in the program. Personally I like to swap numbers through XORing operator as it eliminates extra variables which in returns make program size shorter and run faster. Also no need to write a another function and eliminates many statements. 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s