next up previous contents
Next: Examples of Loop Counts Up: Control Flow Previous: DO ... WHILE Loops

 

Indexed DO Loop

Loops can be written which cycle a fixed number of times. For example,

    DO i = 1, 100, 1
     ...
    END DO

is a DO loop that will execute 10 times, it is exactly equivalent to

    DO i = 1, 100
     ...
    END DO

The syntax is as follows,

 
DO < DO-var >=< expr1 >,< expr2 > [ ,< expr3 > ]
  
		 < exec-stmts >

END DO

The loop can be named and the < exec-stmts > could contain EXIT or CYCLE statements, however, a WHILE clause cannot be used but this can be simulated with an EXIT statement if desired.

The number of iterations, which is evaluated before execution of the loop begins, is calculated as

 
MAX(INT((< expr2 >-< expr1 >+< expr3 >)/< expr3 >),0)

in other words the loop runs from < expr1 > to < expr2 > in steps of < expr3 >. If this gives a zero or negative count then the loop is not executedgif.

If < expr3 > is absent it is assumed to be 1.

The iteration count is worked out as follows (adapted from the standard, [1]):

  1. < expr1 > is calculated,
  2. < expr2 > is calculated,
  3. < expr3 >, if present, is calculated,
  4. the DO variable is assigned the value of < expr1 >,
  5. the iteration count is established (using the formula given above).

The execution cycle is performed as follows (adapted from the standard):

  1. the iteration count is tested and if it is zero then the loop terminates.
  2. if it is non zero the loop is executed.
  3. (conceptually) at the END DO the iteration count is decreased by one and the DO variable is incremented by < expr3 >gif.
  4. control passes to the top of the loop again and the cycle begins again.

More complex examples may involve expressions and loops running from high to low:

    DO i1 = 24, k*j, -1
     DO i2 = k, k*j, j/k
      ...
     END DO
    END DO

An indexed loop could be achieved using an induction variable and EXIT statement, however, the indexed DO loop is better suited as there is less scope for error.

The DO variable cannot be assigned to within the loop.

Return to corresponding overview page gif




next up previous contents
Next: Examples of Loop Counts Up: Control Flow Previous: DO ... WHILE Loops

©University of Liverpool, 1997
Wed May 28 20:20:27 BST 1997
Not for commercial use.