Fortran Do While, Exit & Cycle
Counted loops are not always enough. Sometimes you don't know in advance how many iterations you need: iterate until a result converges, read until the end of a file, or search until you find something. Fortran offers do while, the endless do with exit, and cycle to skip to the next iteration.
do while
do while (condition) checks the condition before each iteration and stops as soon as it is false:
program halving
implicit none
real :: amount
integer :: years
amount = 1000.0
years = 0
do while (amount > 100.0)
amount = amount * 0.8 ! loses 20% each year
years = years + 1
end do
print '(a, i0, a, f7.2)', 'After ', years, ' years the value is ', amount
end program halvingAfter 11 years the value is 85.90
exit: leave the loop
exit jumps out of the loop immediately. Combined with a do that has no loop control at all, it gives a loop whose test can sit anywhere in the body. This is the idiomatic Fortran form of a while (true) loop:
program collatz
implicit none
integer :: n, steps
n = 27
steps = 0
do
if (n == 1) exit
if (mod(n, 2) == 0) then
n = n / 2
else
n = 3 * n + 1
end if
steps = steps + 1
end do
print '(a, i0, a)', 'Starting from 27, the Collatz sequence reaches 1 after ', steps, ' steps.'
end program collatzStarting from 27, the Collatz sequence reaches 1 after 111 steps.
Tip: An endless
doloop with a convergence test should usually also have a maximum number of iterations, so a bug can't make it run forever. A counted loop withexitdoes both at once:do iter = 1, max_iter … if (converged) exit … end do.
cycle: skip to the next iteration
cycle ends the current iteration and continues with the next one:
program skip_negatives
implicit none
real :: readings(8) = [2.5, -1.0, 3.0, -9.9, 4.5, 0.0, -2.0, 1.0]
real :: total
integer :: i, used
total = 0.0
used = 0
do i = 1, size(readings)
if (readings(i) < 0.0) cycle ! invalid sensor value
total = total + readings(i)
used = used + 1
end do
print '(a, i0, a, f5.2)', 'Used ', used, ' readings, mean = ', total / used
end program skip_negativesUsed 5 readings, mean = 2.20
Named loops
In nested loops, a plain exit or cycle affects only the innermost loop. To leave or continue an outer loop, give it a name and use the name after exit or cycle:
program find_pair
implicit none
integer :: values(6) = [8, 3, 11, 6, 14, 5]
integer :: i, j, target
target = 17
outer: do i = 1, size(values) - 1
do j = i + 1, size(values)
if (values(i) + values(j) == target) then
print '(a, i0, a, i0, a, i0)', 'Found ', values(i), ' + ', values(j), ' = ', target
exit outer ! leave both loops
end if
end do
end do outer
print '(a, i0, a, i0)', 'Stopped at i = ', i, ', j = ', j
end program find_pairFound 3 + 14 = 17
Stopped at i = 2, j = 5
Named cycle works the same way:
program primes
implicit none
integer :: n, d
write(*, '(a)', advance='no') 'Primes below 40:'
candidates: do n = 2, 39
do d = 2, int(sqrt(real(n)))
if (mod(n, d) == 0) cycle candidates ! not prime: try next n
end do
write(*, '(1x, i0)', advance='no') n
end do candidates
print *
end program primesPrimes below 40: 2 3 5 7 11 13 17 19 23 29 31 37
Iterating to convergence
Here is a realistic use: Newton's method for √2. We repeat x = (x + 2/x) / 2 until the change is tiny, with an iteration limit as a safety net.
program newton_sqrt
use iso_fortran_env, only: real64
implicit none
real(real64) :: x, x_new
integer :: iter
x = 1.0_real64
do iter = 1, 50
x_new = 0.5_real64 * (x + 2.0_real64 / x)
print '(a, i2, a, f18.15)', 'iter ', iter, ': ', x_new
if (abs(x_new - x) < 1.0e-14_real64) exit
x = x_new
end do
end program newton_sqrtiter 1: 1.500000000000000
iter 2: 1.416666666666667
iter 3: 1.414215686274510
iter 4: 1.414213562374690
iter 5: 1.414213562373095
iter 6: 1.414213562373095
The number of correct digits roughly doubles with each step, a hallmark of Newton's method.
Test yourself
What does cycle do inside a loop?
- Leaves the loop
- Skips the rest of the current iteration and starts the next one
- Restarts the loop from the beginning
- Pauses the program
In nested loops, how do you leave the outer loop named outer from the inner loop?
exitexit outerbreak outerstop outer
When is the condition of do while (cond) tested?
- After each iteration
- Before each iteration
- Only once
- Only when
cycleruns