1.

How will you swap two numbers without the use of a third variable?

Answer»

This can be achieved using ARITHMETIC operations.

int x = 5, y = 15; // Code to SWAP the values of x and y x = x + y; // x now BECOMES 20 y = x - y; // y becomes 5 x = x - y; // x becomes 15

Or

int x = 5, y = 15; // Code to swap the values of x and y x = x * y; // x now becomes 75 y = x / y; // y becomes 5 x = x / y; // x becomes 15

This can ALSO be achieved using bitwise operations.

int x = 5, y = 15; // Code to swap the values of x and y x = x ^ y; // x now becomes 20 y = x ^ y; // y becomes 5 x = x ^ y; // x becomes 15


Discussion

No Comment Found