In previous post i had mentioned about how to swap two numbers without using temporary variable. But how to swap two numbers without using temporary variable as well as without using arithmetic operators.?
You might have seen this question in any of the coding competitions or technical interviews.
It can be done using xor operator
So i think its quite tricky than the previous question (previous post). Because students will not be familiar with these kind of operators.
So i think it might be helpful for many students or coding geeks..
The code for the same is given below:
#include
void main()
{
//swapping without using temporary variable
//as well as without using arithmetic operators
int a=100,b=200;
printf("\nBefore swapping a:%d, b=%d",a,b);
a=a^b;
b=a^b;
a=a^b;
printf("\nAfter swapping a:%d, b=%d",a,b);
getch();
}
Before swapping a:100, b=200
void main()
{
//swapping without using temporary variable
//as well as without using arithmetic operators
int a=100,b=200;
printf("\nBefore swapping a:%d, b=%d",a,b);
a=a^b;
b=a^b;
a=a^b;
printf("\nAfter swapping a:%d, b=%d",a,b);
getch();
}
output:
Before swapping a:100, b=200
After swapping a:200, b=100
Sweet one Vikas! good one here too:
ReplyDeleteSwap numbers using XOR
Thnaks...
Delete