What is this trying to tell me?

121 views Asked by At

I am reading the book "How to solve it by computer" by RG Dromey. I am stuck on a sentence that is trying to explain termination of loops. Here goes the problem:

Suppose we wish to establish that an array of n elements is in strictly ascending order (i.e. a[1] < a[2] < ... < a[n]) . To do this we can use the following instructions:

a[n+1] := a[n];
i := 1;
while a[i] < a[i+1] do i := i+1

(Now if n is the number of elements, what does i stand for in this case? Does it stand for values?)

If n was assigned the value 5 and the data set was 2, 3, 5, 11, 14, then the first assignment prior to the loop would result in the array configuration below:

(This is where I get confused.)

a[1]  a[2]  a[3]  a[4]  a[5]  a[6]
2     3     5     11    14    14

The two 14's guarantee that the test a[i] < a[i+1] will be false when i = n and so the loop will terminate correctly when i = n if not before.

(This is confusing.)

1

There are 1 answers

7
paparazzo On BEST ANSWER

i is simply the index
i := 1; means i is equal 1
i := i+1 means add 1 to i

n = 5

a[5] = 14
a[5+1] = a[6] = 14

14 < 14 is false - the loop terminates