You need a temporary variable for swapping two values without loosing values:
x <- a
a <- b
b <- x
This is an advanced trick without an additional variable:
a <- a + b
b <- a - b
a <- a - b
To compute the squares of the numbers you have to modify the update statement of acc
:
i ← 0
acc ← 0
REPEAT n TIMES {
i ← i + 1
acc ← acc + i * i
}
For computing the product you have to modify the update rule for acc
as shown below and you have to start with acc ← 1
:
i ← 0
acc ← 1
REPEAT n TIMES {
i ← i + 1
acc ← acc * i
}
The snippet computes $2^n$
The sequence of values for i
and acc
is:
i acc
0 0
1 0
2 2
3 2
4 6