Repetitive Instructions and DO Loops

Repetitive instructions: the DO loop

What is a DO loop?

When doing numerical calculations it is often necessary to do the same calculation many times. An example might be computing the Coriolis parameter at every latitude as in Exercise 5, or finding the solar elevation angle for each hour of the day.

Fortran provides a standardized set of instructions - called a "DO loop" - for performing these repetitive calculations. You could use a DO loop to write a simple program that computes the number of elapsed seconds at each hour of the day, beginning at midnight:

      PROGRAM MAIN
      INTEGER I, SECOND
      DO 10 I = 0, 24
      SECOND = 3600 * I
      PRINT *, 'HOUR = ', I, '  SECONDS =', SECOND
10    CONTINUE
      STOP
      END

How does it work?

The statement beginning with DO controls the instructions that are to be repeated and the number of times they are repeated. We need to look closely at each part of the DO statement, from left to right:

      DO 10 I = 0, 24

A verbal description what happens in a DO loop might be as follows:

Set the index to its initial value. Then, repeat all the instructions from the DO line down to the statement with the given statement number. After these instructions are completed, add 1 to the index. Keep doing this until the index exceeds the limit.

Some details

      DO 10 I = 0, 24, 1

For example, if we wanted to do some calculations every three hours, we would construct a DO statement like:

DO 10 I = 0, 24, 3

This would perform the calculations in the loop for values of I equal to 0, 3, 6 ... up to and including 24.

DO ... END DO

Almost all modern compilers (even for Fortran 77) allow DO loops to be terminated with the END DO statement instead of using a numbered statement. Using this approach the loop in the short program at the top of this page would be written as follows:

      DO I = 0, 24
      SECOND = 3600 * I
      PRINT *, 'HOUR = ', I, '  SECONDS =', SECOND
      END DO

Notice that since there is no numbered termination statement, the DO at the start of the loop is not followed by a statement number.

The DO...END DO construction is slightly simpler. However some DO loops can include hundreds or thousands of statements with multiple levels of nested DO loops. In such cases it is confusing to sort out where each loop starts and ends. A good practice is:

Assignment: Construct a DO loop for the Coriolis parameter computations in the previous exercise.

Next: Progrmming style and readability

Back to the main page for the programming tutorial.