Counted DO loops

A counted loop runs a body a number of times known at entry. Fortran writes it as do i = 1, n and closes it with end do, and the four details that matter are the stride, the trip count, the value the loop variable keeps afterwards and the labelled form that old code uses. This lesson goes through those four with one program.

The block DO

Three numbers set the loop: the first value, the last value and the stride, which is one when it is left out. The header evaluates them once, at entry, and the body runs for a value of the variable that starts at the first and steps toward the last.

The file counted.f90:

program counted implicit none integer :: i, total total = 0 do i = 1, 5 total = total + i end do print *, "1 to 5 :", total total = 0 do i = 1, 10, 3 total = total + i end do print *, "1, 4, 7, 10 :", total total = 0 do i = 10, 1, -4 total = total + i end do print *, "10, 6, 2 :", total total = 0 do i = 5, 1 total = total + i end do print *, "no iterations :", total print *, "i after loop :", i end program counted

The fourth loop has a first value above its last value and a positive stride, so it runs no times at all. The compiler can see that and says so during the build:

gfortran -Wall -Wextra -std=f2018 counted.f90 -o counted

counted.f90:24:13:

24 | do i = 5, 1
| 1
Warning: DO loop at (1) will be executed zero times [-Wzerotrip]

The build succeeds, and the run prints the four sums:

./counted

1 to 5 : 15
1, 4, 7, 10 : 22
10, 6, 2 : 18
no iterations : 0
i after loop : 5

The stride

The third number is the step, and it may be any nonzero integer, positive or negative. The second loop above steps by three and visits 1, 4, 7 and 10; the third steps by minus four from ten and visits 10, 6 and 2. A stride of zero is not a loop that never ends, it is a loop the standard forbids, and the compiler rejects it.

The last value is a bound and not a count: a stride that does not divide the distance stops before it, so do i = 1, 10, 4 visits 1, 5 and 9. A loop that needs the last value itself computes the stride from the count, or uses an array index from 1 to size.

The trip count

The three control expressions are evaluated once, before the first iteration, and the number of trips is fixed at that moment. Changing a bound inside the body does not extend the loop, which is a difference from a while loop and the source of a bug when a program grows an array inside its own loop.

The file trip.f90:

program trip implicit none integer :: i, n, count n = 3 count = 0 do i = 1, n n = 10 count = count + 1 end do print *, "iterations:", count print *, "n now :", n end program trip

gfortran -Wall -Wextra -std=f2018 trip.f90 -o trip
./trip

iterations: 3
n now : 10

Three iterations, and a final n of ten. A loop whose bound must follow the body is a doc problem for the next lesson: do while (i <= n) tests the condition before every iteration and sees the new value.

A loop that runs zero times

A counted loop whose bounds are empty runs a body zero times, which is the correct answer for a loop over an empty array and a bug when a program assumed at least one iteration. The bound arithmetic is defined for that case: the loop variable takes the value of the first expression, which is why i printed 5 and not 1 in the output above.

The warning -Wzerotrip only fires when both bounds are constants, because otherwise the compiler cannot know. In a loop over 1, size(a) the zero-trip case is a real possibility for every empty array, and a sum that starts at zero handles it without a special case, which is the reason the reductions of the array part start there.

The variable after the loop

The standard says the loop variable is undefined after the loop ends normally, and in practice every compiler leaves it one stride past the last value. A program that reads it is relying on an implementation detail, and the habit is to write the count into a separate variable when the count is what is wanted.

Modifying the loop variable inside the body is also forbidden by the standard: the loop increments a private copy and rewrites the variable at the end of each iteration, so an assignment to it is lost. The compiler reports it only with -fcheck=do, which is worth adding to a test build.

The labelled DO of old code

Before Fortran 90 a loop ended at a labelled statement, and the label was written on the right of the header. The form still compiles and still appears in numerical libraries, so a reader has to know it even though new code uses end do.

The file labelled.f90:

C A labelled DO loop in fixed form, the way old code wrote it. PROGRAM LABELLED INTEGER I, TOTAL TOTAL = 0 DO 20 I = 1, 4 TOTAL = TOTAL + I * I 20 CONTINUE PRINT *, "sum of squares:", TOTAL END

gfortran -Wall -Wextra -std=legacy -ffixed-form labelled.f90 -o labelled
./labelled

sum of squares: 30

The 20 in the header names the statement that closes the loop, and the loop variable must not be changed inside it. A nested pair of labelled loops needs two labels and the inner one must close first, which is exactly the bookkeeping end do removes.

Exercises

  1. Write a loop from 1 to 10 with a stride of 4 and print each value. How many lines does it print?
  2. Change the zero-trip loop to do i = 1, 0, -1. How many iterations now, and why?
  3. In the trip-count program, set n = 2 inside the body instead of 10. Does the count change?
  4. Convert the labelled loop to do ... end do and build it with -std=f2018. What changes in the source?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which statement closes a block DO loop?

    Answer

    END DO

    The block form closes with END DO; CONTINUE belongs to the labelled form.

  2. How many times does do i = 1, 10, 3 iterate?

    Answer

    Four times: 1, 4, 7, 10

    The stride of 3 from 1 reaches 10 exactly, and the last bound is included.

  3. When are the loop bounds evaluated?

    Answer

    Once, before the first iteration

    The trip count is fixed at entry, so changing a bound inside the body has no effect.

  4. What does a loop with a positive stride and an empty range do?

    Answer

    It runs zero times and the build warns with -Wzerotrip when the bounds are constant

    An empty range is a zero-trip loop, and gfortran reports it when it can prove it.

  5. What is the loop variable after a normal exit?

    Answer

    Undefined by the standard, and in practice one stride past the last value

    The standard leaves it undefined, so a program must not depend on the value.

  6. What does this program print? program p implicit none integer :: i, s s = 0 do i = 1, 4 s = s + i end do print *, s end program p

    Answer

    10

    The sum of 1 to 4 is 10.

  7. What is the stride of do i = 1, n?

    Answer

    One

    The third control expression defaults to one.

  8. What closes a labelled DO loop?

    Answer

    The statement carrying the label from the header

    The label in the header names the closing statement, usually a CONTINUE.

  9. What happens if the body assigns to the loop variable?

    Answer

    The assignment is lost when the loop increments its own copy

    The standard forbids it, and the loop overwrites the variable each iteration.

  10. Which form should new code use?

    Answer

    do ... end do

    The block form has no label to mismanage and nests without ambiguity.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container. The labelled program was built with -std=legacy -ffixed-form.

Article author: Arthur Isaev