1

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"))

  • I am not sure what is there to nit understand. It is literally a long division by 2. – user58697 Oct 17 '18 at 01:32
  • This is exactly what the algorithm is doing: a long division by 2. – user58697 Oct 17 '18 at 01:53
  • Sory @user58697 I was not clear. I understand the long division by 2 process. I edited the post so my doubt is easier to undestand. If we ´ve an array of k elements, for example k = 3.As we know array´s positions starts in 0 so we ´ve d[0] d[1] d[2]. Why would you assign 5 to the d[3]? and then just print "5"? – Federico R. Figueredo Oct 17 '18 at 17:59

1 Answers1

0

The computation utilizes the fact that the last digit will always be five.

  1. Unless the execution has finished, the variable 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 loop
  2. The statement Texts.Write(W, "5") requires (marginally) less computation than Texts.Write(W, d[i]).
August Karlstrom
  • 10,773
  • 7
  • 38
  • 60