Wednesday, May 5, 2010

Swapping values between two variables without a third variable

Here are two ways in which we can swap the values between two variables without the help of any third(temporary) variable:

-> Using method of Addition:

int main(void)
{
unsigned char A, B;
A = 39;
B = 18;
printf("Before:\tA: %d\tB: %d\n", A, B);
/* Swapping Algorithm */
A = A+B;
printf("A: %d\tB: %d\n", A, B);
B = A-B;
printf("A: %d\tB: %d\n", A, B);
A = A-B;
printf("After:\tA: %d\tB: %d\n", A, B);
return 0;
}

-> Using the method of EXOR:

int main(void)
{
unsigned char A, B;
A = 39;
B = 18;
printf("Before:\tA: %d\tB: %d\n", A, B);
/* Swapping Algorithm */
A ^= B;
printf("A: %d\tB: %d\n", A, B);
B ^= A;
printf("A: %d\tB: %d\n", A, B);
A ^= B;
printf("After:\tA: %d\tB: %d\n", A, B);
return 0;
}

=> NOTE: The maximum range of the value to be stored in the variables A & B should be such that, the value of (A+B) will be inside the maximum range of the data type defined for A & B variables.

=> NOTE: The method of EXOR will not work if a and b both have same values. If a and b both have the same values, then both will get cleared (equal to zero) after swapping.

No comments:

Post a Comment