I've been studying "Algorithms and Data Structures" by N.Wirth. He codes his algorithms in a language he created: Oberon. I finished the book but I have one doubt about this algorithim of page 19 coded in Oberon:
PROCEDURE Power (VAR W: Texts.Writer; N: INTEGER);
VAR i, k, r: INTEGER;
d: ARRAY N OF INTEGER;
BEGIN
FOR k := 0 TO N-1 DO
Texts.Write(W, "."); r := 0;
FOR i := 0 TO k-1 DO
r := 10*r + d[i]; d[i] := r DIV 2; r := r MOD 2;
Texts.Write(W, CHR(d[i] + ORD("0")))
END;
d[k] := 5; Texts.Write(W, "5"); Texts.WriteLn(W)
END
END Power
The resulting output text for N = 10 is
.5
.25
.125
.0625
.03125
.015625
.0078125
.00390625
.001953125
.0009765625
I don´t understand what the instructions in line 10 d[k] := 5; Texts.Write(W, "5"); Texts.WriteLn(W)
does:
1) Why you would you d[k] := 5
? the program already printed all the output required (d[0] to d[k-1]
).
2) why would you print a 5 after that? (Texts.Write(W, "5")
)
The computation utilizes the fact that the last digit will always be five.
d[k]
is read in the next turn of the outer loop when r
becomes 10*r + d[i]
in the last turn of the inner loopTexts.Write(W, "5")
requires (marginally) less computation than Texts.Write(W, d[i])
.