Archived

This topic is now archived and is closed to further replies.

robertocarlos

Interesting Questions, part two!

Recommended Posts

Sorry I wasn''t able to post reply, started new thread. Question: I''m relatively new to programming. Am looking for some programming questions that are interesting Eg. how do you swap 2 no''s without using a third variable. Also questions asked in interviews, to test your programming skills. Any questions or pointers to resources will be appreciated. About swapping: #include <stdio.h> void Swap(int &, int &); int main() { int x,y; printf("Enter 2 no.s :\n"); scanf("%d %d", &x, &y); printf("Two no.s (before) x = %d, y = %d \n",x,y); Swap(x,y); printf("Two no.s (after) x = %d, y = %d \n",x,y); return 0; } void Swap(int &a, int &b) { b = a + b; a = b - a; b = b - a; }

Share this post


Link to post
Share on other sites

    
void Swap(int x, int y)
{
x ^= y;
y ^= x;
x ^= y;
}


[EDIT] by the way my code should only work on int, char, etc., but yours should work for floats and doubles as well


_____________________________

And the Phoenix shall rise from the ashes...

--Thunder_Hawk -- ¦þ
______________________________


[edited by - Thunder_Hawk on July 18, 2002 5:30:24 PM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by Thunder_Hawk

[EDIT] by the way my code should only work on int, char, etc., but yours should work for floats and doubles as well


<font color="00FF00">_____________________________

And the Phoenix shall rise from the ashes...

--Thunder_Hawk -- ¦þ
______________________________</font>

<SPAN CLASS=editedby>[edited by - Thunder_Hawk on July 18, 2002 5:30:24 PM]</SPAN>


No, it also works on floats. You are simply swapping the bits around.

This technique will work on all pod types.

Share this post


Link to post
Share on other sites