Interview- Swamping two variables

This is a simple question that how to swap two values let say a and without using third variable. But this question gets confusing when you are asked to swap negative and positive value together.
Let say a=2
b=-3
Now swap a value into b and b value into a.

So the code will be:-

{
int a;
int b;
a=2;
b=-3;
a=b-a;
b=-(a)+b;
a=a+b;
Console.WriteLine(“a=”+a);

Console.WriteLine(“b=”+b);
}

a=-3
b=2

The good part about this code is that you can enter any value in a or b whether negative or positive it will swap it with ease.

Advertisements

One thought on “Interview- Swamping two variables

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