26.6.08

Swapping two integers without temporary variable.

We can do this thing in many ways, here are some.


int main()
{
int x, y;
printf("Enter x and y values \n");
scanf("%d %d", &x, &y);
printf("X=%d\t Y=%d\n", x, y);
printf("AFTER SWAP \n");

/* Swap using addition and subtraction */
x = x+y;/*Limitation is there addition should */
y = x-y;/* not over flow */
x = x-y;
printf("X=%d\t Y=%d\n", x, y);

/* Swap using multiplication and division */
x = x*y;/* Limitation is, Y should not be zero and*/
y = x/y;/* and x*y should not overflow */
x = x/y;
printf("X=%d\t Y=%d\n", x, y);

/* swap using exclusive OR */
x = x^y;
y = x^y;
x = x^y;
printf("X=%d\t Y=%d\n", x, y);

return 0;
}