Sunday, 14 October 2012

how to swap two numbers without using temporary variable and without using arithmetic operators.?

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();

}


output: 


Before swapping a:100, b=200
After swapping a:200, b=100

Also see my previous post on how to swap two numbers without using temporary variable and using arithmetic operators. 


2 comments: