Swapping two variables in C
By gagana
@gagana (757)
India
15 responses
@anandashok (26)
• United States
12 Jan 07
Yes.. Its very much possible.. You people dont know that.. Too bad..
Ok I will show you how to do it..
Let a and b be two integers.
then the following code will work.
int a , b;
a=5;
b=10; //now a = 5 and b = 10
a=a+b; //now a = 15 and b =10
b=a-b; //now a=15 and b = 5
a=a-b; //now a = 10 and b =5 which is the required output..
:) such an easy answer...
njoy
@anandashok (26)
• United States
15 Jan 07
Copy Cat.. Try out something yourself.. See my post above..
njoy
@tmaheshwari (170)
• India
12 Jan 07
Hi,
It is very easy.
I m writting an example in C. If you can not understand then please let me know.
int main()
{
int i = 5;
int j = 3;
i = i + j;
j = i - j;
i = i - j;
return 0;
}
@tmaheshwari (170)
• India
18 Jan 07
hmm.. my mistake .... but i will give one more solution for the same... :)
@dholey (1383)
• India
20 Jan 07
we can swap to variables without using the third variables as codes are already given (using arithmetical or using bitwise XOR operator) but the thing i want to say is , they are not the standard one THEY CAN NOT BE USE AS AN ALTERNATIVE FOR SWAPPING USING THIRD VARIABLE.
SO THERE IS NO OTHER CORRECT VERSION FOR SWAPPING TWO VARIABLES WITHOUT USING THIRD VARIABLE , i ams now explaining,
do one thing as all of you must have gone throug both codes given here in discussions just try to swap given two variable with given value using those to codes you will come to the conclusion
x=-5;
y=10;
TRY IT YOUR SELF,,,,,, and mark my response as the best response....
@AvizWorld (265)
• India
12 Jan 07
int a= 10, b= 5;
printf("a value %d", b);
printf("b value %d", a);
@anandashok (26)
• United States
12 Jan 07
very wise.. dont be too wise like this buddy :)
1 person likes this
@Hello_Sonu (624)
• India
14 Jan 07
ya u can do that
see this code
a = a + b;
b = a + c;
b = a-c
some thing like that
try it is possible.
@Hello_Sonu (624)
• India
14 Jan 07
ya u wrote right
can u tell me which is the fast loop
for , while or do while.
@rohand (31)
• India
14 Jan 07
void main()
{
int a,b;
coutab;
swap(a,b);
}
Swap(int x,int y)
{
x=x+y;
y=x-y;//to swap y
x=x-y;//to swap x
}
@flikkenni (537)
• Indonesia
12 Jan 07
i am not sure if i can swapping two variables without using temp variable in C. you know variables declared the address of the memory, or a variable has its own place in the memory. so if you swapped it without using temporary variables one of them will be overwrite with the other ones. so i think you need a temporary variables to swap variables in C.
@cyb3rjunk13 (470)
• United States
16 Jan 07
Well that was a good but childish example bro.For loop is the fastest loop.keep posting nice topics.
@thundercat (505)
• United States
12 Jan 07
I agree with the first poster, I'm pretty sure its not possible. Even when you program in assembly or machine code it still requires a temporary variable so I don't see why C would be any different.