next up previous contents
Next: Conditional Cycle Loops Up: Control Flow Previous: Nested and Named IF

 

Conditional Exit Loops

A loop comprises of a block of statements that are executed cyclically. When the end of the loop is reached the block is repeated from the start of the loop. Loops are differentiated by the way they are terminated. Obviously it would not be reasonable to continue cycling a loop forever. There must be some mechanism for a program to exit from a loop and carry on with the instructions following the End-of-loop.

The block of statements making up the loop is delimited by DO and END DO statements. This block is executed as many times as is required. Each time through the loop, the condition is evaluated and the first time it is true the EXIT is performed and processing continues from the statement following the next END DO. Consider,

    i = 0
    DO
      i = i + 1
      IF (i .GT. 100) EXIT
      PRINT*, "I is", i
    END DO
    ! if i>100 control jumps here
    PRINT*, "Loop finished. I now equals", i

this will generate

  I is   1
  I is   2
  I is   3
    ....
  I is   100
  Loop finished. I now equals   101

This type of conditional-exit loop is useful for dealing with situations when we want input data to control the number of times the loop is executed.

The statements between the DO and its corresponding END DO must constitute a proper block. The statements may be labelled but no transfer of control to such a statement is permitted from outside the loop-block. The loop-block may contain other block constructs, for example, DO, IF or CASE, but they must be contained completely; that is they must be properly nested.

An EXIT statement which is not within a loop is an error.

Return to corresponding overview page gif


next up previous contents
Next: Conditional Cycle Loops Up: Control Flow Previous: Nested and Named IF

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