The LOOP construct provides a two-tiered structure for repeated execution of a group of statements.
Format
LOOP [statements1] WHILE | UNTIL expr DO [statements2] REPEAT |
Parameter(s)
LOOP |
Starts a program loop. The first group of statements [statements1] is executed, and when the WHILE or UNTIL clause is reached, a test is performed. Depending on the result, execution continues either with the second group of statements [statements2] or with the statements following the REPEAT clause. If an EXIT statement occurs within [statements2], then control is transferred to the statement following the REPEAT of the currently active LOOP/REPEAT structure. This is particularly useful when used in expressions such as READNEXT ID ELSE EXIT. |
WHILE |
This clause allows a positive condition to be specified: as long as this condition is true (i.e., evaluates to 1), the loop repeats. |
UNTIL |
This clause allows a negative condition to be specified: the loop repeats as long as the specified condition is not true (i.e., evaluates to 0). |
DO |
Optional. |
EXIT |
Transfers control. |
REPEAT |
Ends the program loop. |
Description
Any statements included between the LOOP and the WHILE or UNTIL clause are executed at least once; they are repeated again each time the loop is iterated. The statements between the WHILE and UNTIL are executed only if the condition passes; they are repeated each time the loop is iterated, but only if the condition passes in each iteration.
Although it is possible to exit the loop by means other than the conditional WHILE and UNTIL statements (for example, by using GOTO or GOSUB in the DO statements), it is not recommended to do so.
NOTE |
The WHILE/UNTIL statement’s DO clause is no longer mandatory, and may be omitted if it is not necessary. |
Example
This code segment loops on multiplying two user-supplied numbers, NUM1 and NUM2. The loop ends when ‘0’ is input as the value for NUM1. Within this main loop are two loops, one to continue to prompt for NUM1 until a valid number is entered, the other to do the same for NUM2.
LOOP LOOP PRINT "ENTER A NUMBER (ENTER 0 TO EXIT) : " : INPUT NUM1 UNTIL NUM(NUM1) DO PRINT NUM1 : " : NOT A NUMBER. USE 0 TO EXIT" REPEAT UNTIL NUM1 = 0 DO LOOP PRINT "ENTER A SECOND NUMBER : " : INPUT NUM2 UNTIL NUM(NUM2) DO PRINT NUM2 : " : NOT A NUMBER" REPEAT PRINT NUM1 : " TIMES " : NUM2 : " IS " : NUM1*NUM2 : "." REPEAT |
See Also