Possible Duplicate:
Swapping two variable value without using 3rd variable
we have
int a=4;
int b=7;
can i swap these no.s without using third variable?
Possible Duplicate:
Swapping two variable value without using 3rd variable
we have
int a=4;
int b=7;
can i swap these no.s without using third variable?
The precise implementation of course depends on the programming language you're using, but check out XOR swap.
An example in C could be
#include <stdio.h>
/* Swaps the content pointed to by a and b. The memory pointed to is
assumed non-overlapping! */
void swap(int* a, int* b)
{
*a = (*a)^(*b);
*b = (*a)^(*b);
*a = (*a)^(*b);
}
int main(int argc, char** argv)
{
int a = 4;
int b = 7;
printf("a=%d, b=%d\n", a, b);
swap(&a, &b);
printf("a=%d, b=%d\n", a, b);
return 0;
}
Important: As Prasoon Saurav commented on the question itself, this answer to another question is more correct than mine, seeing as it is important that the two variables reside at non-overlapping locations in memory. My example does not check for this.
a=a+b; //a=11,b=7
b=a-b; //a=11,b4
a=a-b; //a=7,b=4
or
a=a*b;
b=a/b;
a=b/a;
but careful with this method, overflow or underflow is possible for some combinations.