Usually, when we want to exchange two variables, we would think of adding a temp variable. However, there is a way to avoiding the use of extra memory.
Example:
x =a, y = b
step 1:
x := x +y
x = a+b, y =b
step 2:
y := x -y =(a+b) - b = a
x = a+b, y=a
step 1:
x := x +y
x = a+b, y =b
step 2:
y := x -y =(a+b) - b = a
x = a+b, y=a
step 3:
x := x - y = (a+b) - a = b
x = b, y=a
x := x - y = (a+b) - a = b
x = b, y=a
No comments:
Post a Comment