About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Wednesday, September 4, 2013

C Program to Swap two numbers using XOR Operator

Generally Swaping two number requires three variables , Let’s Take look atProcedure of swaping two Number
For Swaping Two numbers following procedure is used -
x = x ^ y --> x^=y -- (1)
y = y ^ x --> y^=x -- (2)
x = x ^ y --> x^=y -- (3)
Now we will Explaining above three statements using example ….
Let x = 12 and y = 9 [ For our sake and simplicity consider number is of 4 bits ]
x = 1100
y = 1001

X-OR Table :
  A   B  A X-OR B
110
101
011
000
Step 1 : After : x = x ^ y
x   = 1100
y   = 1001
----------
x^y = 0101
----------
x   = 0101    ..... New Value of x
Step 2 : After y = y ^ x
x   = 0101    ..... New Value is taken
y   = 1001    ..... Old Value of Y
----------
y^x = 1100
----------
y   = 1100    ..... New Value of y = Initial x
Step 3 : After x = x ^ y
x   = 0101    ..... New Value from step 1
y   = 1100    ..... New Value of y from Step 2
----------
y^x = 1001
----------
x   = 1001    ..... New Value of x = Initial y
Here is Program for : [Swap / Interchange two variables [numbers] without using Third Variable]
#include
#include
void main()
{
int num1,num2;

printf("\nEnter First Number : ");
scanf("%d",&num1);

printf("\nEnter Second Number : ");
scanf("%d",&num2);

num1 = num1 ^ num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;

printf("\nNumbers after Exchange : ");
printf("num1 = %d and num2 = %d",num1,num2);

getch();
}
Output :
Enter First Number : 20
Enter Second Number : 40

Numbers after Exchange : num1 = 40 and num2 = 20

1 comment:

zzzzz said...

Algorithm to swap two numbers using Xor bitwise operator in C program.
Let A and B are two C variable
A = A ^ B
B = A ^ B;
A = A ^ B;
or A ^= B ^= A ^= B;