Nested Loops In addition to the rules which apply to single loops, the following rules
apply to nested loops:
Each nested FOR-NEXT loop must begin with its own FOR-TO statement
and end with its own NEXT statement.
An outer loop and an inner (nested) loop cannot have the same
running variable.
Each inner (nested) loop must be completely embedded within an outer
loop, the loops cannot overlap.
Control can be transferred from an inner loop to a statement in an outer
loop or to a statement outside of the entire nest. However, control cannot
be transferred to a statement within a nest from a point outside the
nest.
The following example shows the structure of a nested loop.
Example:
The inner loop (statements 90 through 115) is completely embedded within
the outer loop (statements 65 through 140). Each loop begins and
ends with its own FOR-TO and NEXT statements, and each loop
has its own running variable. You will notice the running variable of
the outer loop (X) is used as the initial value for the running variable
of the inner loop (Y). This is allowed since the value of X is not changed
within the inner loop.
By using nested loops, you are able to perform repeated sets of instructions
within another set of instructions.
Example:
The outer loop (lines 30-1 10) will be executed 10 times, while the inner
loop (lines 60-90) will be executed 3 times for
each time the outer loop is executed. This
means the inner loop is executed a total of 30 times.
|