JIGYASA

An online placement forum.


You are not connected. Please login or register

@Swap2Var@

Go down  Message [Page 1 of 1]

1 @Swap2Var@ on Wed Mar 10, 2010 1:34 am

Write a sample code to swap two variables without using a temporary variable

View user profile

2 Swap Function on Wed Mar 10, 2010 3:48 pm

void swap(int x, int y)
{
x -= y;
y += x; // y gets the original value of x
x = (y - x); // x gets the original value of y
}

View user profile

3 Re: @Swap2Var@ on Wed Mar 10, 2010 4:18 pm

Correct. And this is the only solution which works for all pairs of integers (+ve/-ve)

View user profile

4 @i2aguru@ on Wed Mar 10, 2010 4:51 pm

Lucifer


Admin
Well i don't completely agree with your statement. There are other solutions to the same problem which are capable of handling both +ive and -ve inputs.

View user profile http://jigyasa.forumn.org

5 @Lucifer on Wed Mar 10, 2010 4:54 pm

Of Course there are many other ways. Can you share one example here ?

View user profile

6 @arubuee on Wed Mar 10, 2010 4:54 pm

Lucifer


Admin
just curious... if i make a call to ur function using the below snippet what will be the output...

int x =5, y =6;
swap(x,y);
printf("%d %d", x,y);

View user profile http://jigyasa.forumn.org

7 @i2aguru on Wed Mar 10, 2010 4:56 pm

Lucifer


Admin
XOR can be used to do the same...

x ^= y;
y ^= x;
x ^= y;

View user profile http://jigyasa.forumn.org

8 @lucifer on Thu Mar 11, 2010 12:38 am

Question
The output for your snippet will be
5,6
The swap wont work here because it is 'pass by value'
instead if we use
swap(*x,*y)- pass by reference
The swapping will work fine.

View user profile

9 Re: @Swap2Var@ on Sat May 01, 2010 2:28 pm

void swap(int x,int y)
{
x=x+y;
y=x-y;
x=x-y;
}

View user profile

Sponsored content


Back to top  Message [Page 1 of 1]

Permissions in this forum:
You cannot reply to topics in this forum