We have seen two further versions of the DO construct:
DO
IF (logical-expr) EXIT
block
END DO
and
DO
block
IF (logical-expr) EXIT
END DO
(both versions may be named).
The EXIT statement provides a means to exit from an otherwise endless loop. It may in fact go anywhere in the loop. However, it is best for it to go either at the top or at the end; the reader does not then have to search through the loop to find the exit condition.
Some purists might argue that the EXIT should always be at the top of such a non-deterministic loop, so that it is clear to a reader how a loop will end when she first encounters it. The while-do construct of languages like Pascal lends itself more readily to this convention. The way Fortran 90 is designed makes it more natural to put the EXIT at the end. However, I am sure you are old enough to decide for yourself!
There is one situation in which the EXIT must be at the top of the loop, and this is when a zero trip count is logically possible. An example is the original form of the guessing game above: if the user guesses the number correctly first time, there should be no executions of the DO block.
See also
- Category:Fortran
- How to use R/Tutorials/Connecting Fortran and R