JIGYASA
Would you like to react to this message? Create an account in a few clicks or log in to continue.
JIGYASA

An online placement forum.


You are not connected. Please login or register

@Swap2Var@

5 posters

Go down  Message [Page 1 of 1]

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

i2aGuru



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

2@Swap2Var@ Empty Swap Function Wed Mar 10, 2010 3:48 pm

arubuee



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
}

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

i2aGuru



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

4@Swap2Var@ Empty @i2aguru@ 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.

https://jigyasa.forumotion.com

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

i2aGuru



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

6@Swap2Var@ Empty @arubuee 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);

https://jigyasa.forumotion.com

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

Lucifer


Admin

XOR can be used to do the same...

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

https://jigyasa.forumotion.com

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

whyNot



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.

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

pro



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

Sponsored content



Back to top  Message [Page 1 of 1]

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