LOOP
statements
END LOOP
This form sets up an infinite loop, but an additional statement, BREAK, may
be used to terminate the loop. BREAK would, of course, normally have to
be inside an IF structure.
PROC COUNT
{ A procedure to print the numbers from 1 to 10 }
I = 1
LOOP
PRINT (I)
I = I+1
IF I > 10
BREAK
ENDIF
ENDLOOP
ENDPROC
As it is frequently required to loop over a sequential range of numbers in
this way, a special form of the LOOP statement is provided for this purpose.
It has the following form:
LOOP FOR variable = expression1 TO expression2 [ STEP expression3 ]
statements
END LOOP
This form is essentially equivalent to the DO loop in FORTRAN. The expressions
specifying the range of values for the control variable are rounded to the
nearest integer so that the variable always has integer values. Using this
form of the LOOP statement we can simplify the previous example as
follows:
PROC COUNT
{ A procedure to print the numbers from 1 to 10 }
LOOP FOR I = 1 TO 10
PRINT (I)
ENDLOOP
ENDPROC
Note that there is an optional STEP clause in the LOOP FOR statement. If
this is not specified a STEP of 1 is assumed. The STEP clause can be used
to specify a different value. A step of -1 must be specified to get a loop
which counts down from a high value to a lower value. For example:
LOOP FOR I = 10 TO 1 STEP -1
will count down from 10 to 1.
The third form of the LOOP structure allows the setting up of loops which terminate on any general condition. It has the form:
LOOP WHILE expression
statements
END LOOP
The expression is evaluated each time round the loop, and if it has the logical
value TRUE the statements which form the body of the loop are executed. If
it has the value FALSE execution continues with the statement following
END LOOP.
Using this form we can write yet another version of the COUNT procedure:
PROC COUNT
{ A procedure to print the numbers from 1 to 10 }
I = 1
LOOP WHILE I <= 10
PRINT (I)
I = I+1
ENDLOOP
ENDPROC
In the above case the LOOP WHILE form is more complicated than the LOOP FOR
form. However LOOP WHILE can be used to express more general forms of loop
where the termination condition is something derived inside the loop. An
example is a program which prompts the user for an answer to a question
(e.g. yes or no) and has to keep repeating the prompt until a valid
answer is received.
FINISHED = FALSE
LOOP WHILE NOT FINISHED
INPUT Enter YES or NO: (ANSWER)
FINISHED = ANSWER = 'YES' OR ANSWER = 'NO'
END LOOP
ICL The Interactive Command Language for ADAM