Subsections

- Exercises

# Loops revisited

In section 3.7, we introduced the loop clause whose start, step and finish were specified by integer denotations. Instead of an integer, a unit which yields a value of mode `INT` in a meek context can be supplied. The principle coercions not available in a meek context are rowing and widening. In practice, almost any unit yielding `INT` will do. In particular, a name with mode `REF INT` can be given.

There is an extra construct which is extremely useful for controlling the execution of the `DO` ... `OD` loop. It is very common to execute a loop while a particular condition holds. For example, while integers are negative:

       WHILE
          REF INT int=LOC INT; read(int); int < 0
       DO
          print((ABS int,newline))
       OD

In this example, no loop counter was needed and so the `FOR id` part was omitted. The phrase following the `WHILE` must be an enquiry clause yielding `BOOL`. In this case, an integer is read each time the loop is elaborated until a non-negative integer is read. The range of any declarations in the enquiry clause extends to the `DO` ... `OD` loop.

It happens quite often that the `WHILE` enquiry clause performs all the actions which need repeating and nothing is required in the `DO` part. Since the loop clause must contain at least one unit, `SKIP` can be used as in

       FOR i FROM LWB a TO UPB a
       WHILE (sum+:=a[i]) <= max
       DO
          SKIP
       OD

The complete loop clause thus takes the form:

       FOR id FROM from-unit BY by-unit TO to-unit
       WHILE boolean-enquiry-clause
       DO
          serial clause
       OD

## Exercises

5.17
  Write a program which will read integers until zero is encountered. The program should print the sums of the negative and positive integers. Ans
5.18
  Write a program which will read lines from the keyboard and then compute a unique code for each line as follows: if `"did"` is read, compute the value of

         ABS"d" + ABS"i"*2 + ABS"d"*3

  Display the string and its corresponding number on the screen. Terminate the program when a zero-length line has been read (if the result exceeds `max int`, you will normally not get an error: just erroneous results--see section 13.3.13). Ans