Combining Types of Loops
You can combine repetitive and conditional loops to create a compound loop. The
following loop is set to repeat 10 times while a certain condition is met, at which
point it stops.
quantity = 20
DO number=1TO10WHILE quantity < 50
quantity = quantity + number
SAY 'Quantity = 'quantity ' (Loop 'number')'
END
The result of this example is as follows:
Quantity = 21 (Loop 1)
Quantity = 23 (Loop 2)
Quantity = 26 (Loop 3)
Quantity = 30 (Loop 4)
Quantity = 35 (Loop 5)
Quantity = 41 (Loop 6)
Quantity = 48 (Loop 7)
Quantity = 56 (Loop 8)
You can substitute a DO UNTIL loop, change the comparison operator from < to >,
and get the same results.
quantity = 20
DO number=1TO10UNTIL quantity > 50
quantity = quantity + number
SAY 'Quantity = 'quantity ' (Loop 'number')'
END
Nested DO Loops
Like nested IF/THEN/ELSE instructions, DO loops can also be within other DO
loops. A simple example follows:
DO outer=1TO2
DO inner=1TO2
SAY 'HIP'
END
SAY 'HURRAH'
END
The output from this example is:
HIP
HIP
HURRAH
HIP
HIP
HURRAH
If you need to leave a loop when a certain condition arises, use the LEAVE
instruction followed by the control variable of the loop. If the LEAVE instruction is for
the inner loop, you leave the inner loop and go to the outer loop. If the LEAVE
instruction is for the outer loop, you leave both loops.
To leave the inner loop in the preceding example, add an IF/THEN/ELSE instruction
that includes a LEAVE instruction after the IF instruction.
DO outer=1TO2
DO inner=1TO2
IF inner > 1 THEN
LEAVE inner
Using Looping Instructions
Chapter 4. Controlling the Flow Within an Exec 55