Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Control Flow

do Loops

Repeat work in Fortran with counted do loops, steps and countdowns, do while, endless do with exit, nested loops, the trip count rule and implied do loops for printing.

Loops repeat a block of statements. Fortran has one loop keyword, do, with several forms: a counted loop with an index variable, a do while loop that runs as long as a condition holds, and an endless loop you leave with exit. This lesson covers all of them, plus the details that trip up newcomers, like the trip count and the rule that you must not modify the loop variable.

The counted do loop

FORTRAN
program count_demo
  implicit none
  integer :: i

  do i = 1, 5
    print *, "i =", i
  end do
end program count_demo

The loop variable i starts at 1 and runs through 5 inclusive, printing five lines. The general form is do var = start, stop [, step]. After the loop finishes normally, i holds the first value that was not executed, here 6.

Always declare the loop variable as an integer. (Real loop variables were removed from the standard because of rounding trouble.)

Steps and countdowns

The optional third number is the step, which may be negative but never zero:

FORTRAN
do i = 0, 20, 5        ! 0 5 10 15 20
  print *, i
end do

do i = 10, 1, -3       ! 10 7 4 1
  print *, i
end do

The loop runs zero times when the bounds are already "past" each other: do i = 5, 1 does nothing because the default step is +1.

The trip count

At the start, Fortran computes how many times the body will run:

trips = max( (stop - start + step) / step , 0 ) using integer division.

It is fixed before the first iteration. Changing stop or step variables inside the body has no effect on the number of passes, because the values were copied. Modifying the loop variable itself is forbidden, and the compiler may reject it. If you want a different pattern, use do while or an endless loop.

Python Stand-in (Python): trip count and final loop variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

do while

do while (condition) repeats as long as the condition is true. The condition is checked before each pass:

FORTRAN
program halve
  implicit none
  real :: x

  x = 100.0
  do while (x > 1.0)
    x = x / 2.0
    print *, x
  end do
end program halve

It halves 100 until the value drops to 1 or below. Make sure something inside the loop changes the condition, or the loop never ends. Many Fortran programmers prefer the endless form with exit instead of do while, because the exit test can sit anywhere in the body.

The endless loop and exit

A do with no control part repeats forever until an exit statement jumps out:

FORTRAN
program guess
  implicit none
  integer :: secret, tries, g

  secret = 7
  tries = 0
  do
    tries = tries + 1
    g = tries * 3 - 2          ! stand-in for user guesses: 1, 4, 7, ...
    if (g == secret) exit
  end do
  print *, "Found after", tries, "tries"
end program guess

It finds 7 on the third try and prints that. The next lesson, exit, cycle and named constructs, covers exit and cycle in depth, including how to leave an outer loop from an inner one.

Python Stand-in (Python): endless loop with exit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Nested loops

A loop inside a loop runs its full cycle for each pass of the outer one. Each loop needs its own variable:

FORTRAN
program table
  implicit none
  integer :: row, col

  do row = 1, 3
    do col = 1, 4
      write (*, "(I4)", advance="no") row * col
    end do
    write (*, *)                ! end the line
  end do
end program table

The output is a multiplication table:

TEXT
   1   2   3   4
   2   4   6   8
   3   6   9  12

The advance="no" keeps all four numbers of a row on one line, and the empty write (*, *) finishes the line.

Python Stand-in (Python): nested loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Implied do loops

For printing or filling lists there is a compact one-line loop, the implied do, written (expression, var = start, stop [, step]):

FORTRAN
print *, (i * i, i = 1, 5)             ! 1 4 9 16 25
print "(5I4)", (i, i = 10, 50, 10)     ! 10 20 30 40 50

It is also how you build arrays: squares = [(i * i, i = 1, 10)] creates an array of ten squares. You will use this constantly in the arrays chapter.

Accumulating and counting: the two patterns

Most loops either accumulate into a variable or count matches. Initialize before the loop, update inside it:

FORTRAN
integer :: i, total, evens

total = 0
evens = 0
do i = 1, 100
  total = total + i
  if (mod(i, 2) == 0) evens = evens + 1
end do
print *, total, evens          ! 5050 50

Forgetting the initialization is the classic bug: an uninitialized total starts as garbage.

Python Stand-in (Python): accumulate and count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Changing the loop variable inside the loop (not allowed).
  • Off-by-one: do i = 1, n runs n times with i from 1 to n inclusive, unlike zero-based loops in C.
  • Real loop counters: use an integer and compute the real value from it: x = x0 + (i - 1) * dx.
  • Missing exit in an endless loop.
  • Mismatched names when loops are named (see the next lesson).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

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

    i takes the values 2, 5 and 8; the next value, 11, exceeds 10. The formula (10 - 2 + 3) / 3 gives 3.
  2. 2. What value does i hold after do i = 1, 5 ... end do finishes normally?

    After normal completion the loop variable holds the first value that was not executed, here 6.
  3. 3. Which statement leaves an endless do loop?

    exit leaves the innermost enclosing do construct.
  4. 4. What does (i * i, i = 1, 4) produce in a print list?

    An implied do evaluates the expression for each value of i and yields the values 1, 4, 9 and 16.

Summary

  • do i = start, stop [, step] runs a fixed number of times, with both bounds included.
  • The trip count is computed once, before the first pass; never change the loop variable inside.
  • do while (cond) tests first; an endless do ends with exit.
  • Nested loops need distinct variables; advance="no" builds table rows.
  • Implied do loops generate lists and arrays in one line.

Next: exit, cycle and Named Constructs