DO WHILE and named loops
A counted loop knows how many times it runs. A loop that tests a condition before every iteration does not, and that is the right shape for a computation that stops when it is good enough. Fortran writes it with do while, and both kinds of loop can carry a name. This lesson covers the loop, the convergence pattern that needs a second stop condition, and the names.
DO WHILE
The header takes one logical expression, and the body runs while the expression is true. The test happens before every iteration, including the first, so a condition that starts false runs the body zero times.
The file while_loop.f90:
program while_loop
implicit none
real :: x
integer :: steps
x = 100.0
steps = 0
do while (x > 1.0)
x = x / 2.0
steps = steps + 1
end do
print *, "steps:", steps
print *, "x :", x
end program while_loop
gfortran -Wall -Wextra -std=f2018 while_loop.f90 -o while_loop
./while_loop
steps: 7
x : 0.781250000
Seven halvings take a hundred below one: 50, 25, 12.5, 6.25, 3.125, 1.5625 and 0.78125. The loop ends at the first value that fails the test, and the value is still stored in x after the loop, which is how a loop like this returns its answer.
A convergence loop
The pattern a numerical program actually uses has two stop conditions: the answer is good enough, or the iterations ran out. Both belong in the header, joined with .and., because Fortran evaluates both sides and the iteration counter must be read every time anyway.
The file newton.f90:
program newton
implicit none
real :: x, next
integer :: iter
x = 2.0
iter = 0
do while (abs(x * x - 2.0) > 1.0e-6 .and. iter < 20)
next = 0.5 * (x + 2.0 / x)
x = next
iter = iter + 1
end do
print *, "sqrt(2) ~", x
print *, "iterations:", iter
end program newton
gfortran -Wall -Wextra -std=f2018 newton.f90 -o newton
./newton
sqrt(2) ~ 1.41421354
iterations: 4
Newton's method for the square root converges in four steps from a starting value of two, and the loop stops on the tolerance rather than on the counter. The counter is not decoration: a method that diverges, or a tolerance below what single precision can reach, would otherwise loop forever, and a program that never returns is worse than one that returns a wrong answer.
The tolerance is checked against the residual x * x - 2 and not against the change in x, because the residual is the quantity the problem is about. A loop that stops when two successive values agree can stop on a plateau that is not a solution.
Names on loops
A do may carry a name, and the matching end do repeats it. With one loop the name is noise; with two nested loops it is the only way for the reader to see which header a given end belongs to, especially in a long body.
The file named.f90:
program named
implicit none
integer :: i, j
outer: do i = 1, 2
inner: do j = 1, 3
print *, "i, j:", i, j
end do inner
end do outer
end program named
gfortran -Wall -Wextra -std=f2018 named.f90 -o named
./named
i, j: 1 1
i, j: 1 2
i, j: 1 3
i, j: 2 1
i, j: 2 2
i, j: 2 3
The name is a label of the construct and not a variable: it does not appear in any expression and it cannot be printed. Its second job is in exit and cycle, where naming the loop says which loop to leave, and the next lesson uses it for that.
When to use which
- Use a counted do when the number of iterations follows from the data: an array, a grid, a range of indices. The count is then visible in the header and the array bounds check themselves.
- Use do while when the condition is a property of the computation: a residual above a tolerance, a value that has not converged, a queue that still has items.
- Never write a counted loop with a huge upper bound as a substitute for a while: the reader cannot see which of the two stop conditions the program expects to hit.
- Give a convergence loop a cap. The cap turns an infinite loop into a wrong answer, and a wrong answer is something a test can see.
Exercises
- Start the halving loop at 0.5 instead of 100. How many steps, and does the body run at all?
- Set the iteration cap of the Newton loop to 2. What does the program print, and is it a bug?
- Change the tolerance to 1.0e-8. Does the loop still stop on the tolerance, or on the cap?
- Add a third level of nested loops with a name and an end do for each. Which name would a reader need first?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
When is the condition of
do whiletested?Answer
Before every iteration, including the first
A false condition at entry runs the body zero times.
-
Why does a convergence loop need an iteration cap?
Answer
So a method that fails to converge ends with a wrong answer instead of never returning
A cap turns an infinite loop into a result a test can detect.
-
What does a name on a DO construct do?
Answer
It labels the construct for END DO, EXIT and CYCLE
The name is a construct label, not a variable.
-
Which loop fits a computation that stops when a residual is small?
Answer
DO WHILE with the residual and an iteration cap
The condition is a property of the computation, and the cap bounds the run.
-
What does this program print?
program p implicit none integer :: i i = 0 do while (i < 3) i = i + 1 end do print *, i end program pAnswer
3
The body runs for i = 0, 1 and 2, and the loop ends with i = 3.
-
How does a DO WHILE differ from a counted DO in the number of iterations?
Answer
The while loop decides at every iteration; the counted loop fixes the count at entry
The counted loop computes its trip count once; the while loop re-tests each time.
-
What happens when the condition of
do whileis false at entry?Answer
The body runs zero times
The test comes before the first iteration, so a false condition skips the body.
-
Why check the residual rather than the change in x?
Answer
A method can stop changing on a plateau that is not a solution
The residual measures the problem; a small step may be a stall.
-
Which condition pair is written in one header?
Answer
abs(x*x - 2) > tol .and. iter < max_iter
The loop continues while neither stop condition has fired.
-
What is the name on a loop used for in the next lesson?
Answer
EXIT and CYCLE, to name which loop to leave or skip
A named EXIT leaves that construct rather than the innermost one.
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.
Article author: Arthur Isaev