So, the standard way of swapping variables is to use a temporary variable:
int x = 5; int y = 7; int temp = 0;
temp = x;
x = y;
y = temp;
However, are you able to swap the variables without using a temporary variable?
Solution 1: using arithmatic
As x-x = 0, then x is equal to (x+y) – y, and y is equal to (x+y)-x.
So, using the above properties (I will use a ‘->’ for assignment and ‘=’ for equals):
x’ -> x+y
y’ -> x’-y = (x+y) – y
x’ -> x’ – y’ = (x+y) – y’
You will find the numbers have been swapped.
Solution 2: using exclusive or (XOR)
XOR (^) has the following properties:
x^x = 0
x^0 = x
(x^y)^z = x^(y^z)
So using these properties
x’ -> x^y
y’ -> (x^y)^y = x’^y = x
x’ -> x’^y’ = (x^y)^y’
You will also now find the numbers have been swapped.