General DO-Loop with EXIT

The general DO-loop is actually very simple. But, to use it properly, you need to be very careful, since it may never stop. The general DO-loop has a form as follows:

DO
   statements
END DO
Between DO and END DO, there are statements. These statements are executed over and over without any chance to get out of the DO-loop. Here is an example,

REAL  :: x, y, z
DO
   READ(*,*)  x
   y = x*x
   z = x*x*x
   WRITE(*,*)  x, ' square = ', y, ' cube  = ', z
END DO
One iteration of this loop consists of reading a value for x, computing its square and cube to y and z, respectively, and displaying the results. Then, the execution goes back to the top and executes the four statements again. Consequently, this loop is executed over and over and has no chance to stop at all. A loop that never stops is usually referred to as an infinite loop. To stop the iteration of a DO-loop, we need something else.

The EXIT Statement

The EXIT is as simple as writing down the word EXIT. It is used to bail out the containing loop.
DO
   statements-1
   EXIT
   statements-2
END DO
In the above, statements-1 is executed followed by the EXIT statement. Once the EXIT statement is reached, the control leaves the inner-most DO-loop that contains the EXIT statement. Therefore, in the above case, statements-2 will never be executed.

Since it must be some reason for bailing out a DO-loop, the EXIT statement is usually used with an IF or even an IF-THEN-ELSE-END IF statement in one of the following forms. Note that these are not the only cases in which you can use EXIT.

DO
   statements-1
   IF (logical-expression)  EXIT
   statements-2
END DO


DO
   statements-1
   IF (logical-expression) THEN
      statements-THEN
      EXIT
   END IF
   statements-2
END DO
For each iteration, statements in statements-1 are executed, followed the evaluation of the logical-expression. If the result is .FALSE., statements in statements-2 are executed. This completes one iteration and the control goes back to the top and executes statements-1 again for next iteration.

If the result of evaluating logical-expression is .TRUE., the first form will executes EXIT, which immediately stops the execution of the DO-loop. The next statement to be executed is the one following END DO.

For the second form, if the result of evaluating logical-expression is .TRUE., statements in statements-THEN are executed followed by the EXIT statement, which brings the execution to the statement following END DO. Therefore, statements in statements-THEN will do some "house-keeping" work before leaving the DO-loop. If there is no "house-keeping" work, the first form will suffice.

Examples

Some Helpful Notes