Repetitive Instructions and DO Loops

When doing numerical calculations it is often necessary to do the same calculation many times. An example might be computing 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. An example of a repeated calculation using a DO loop could be a simple program to compute 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

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.

Update. Fortran 90 and later now allows 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.

Assignment: Construct a DO loop around the solar elevation computations in the previous exercise, so that you compute the solar elevation angle at each hour of the day.