DO loops
Counted loops
A counted loop runs a fixed number of times with an integer counter that steps from the start to the end.
The loop closes with end do, and the counter is a normal variable that can be printed or used in math inside the loop.
program dodemo
implicit none
integer :: i
do i = 1, 5
print *, "i =", i
end do
end program dodemo
DO WHILE
DO WHILE repeats while a logical test stays true, which fits input checks and convergence loops.
Change the tested value inside the loop, or the loop will never finish.
program whiledemo
implicit none
integer :: n
n = 1
do while (n <= 8)
n = n * 2
end do
print *, "n =", n
end program whiledemo
EXIT and CYCLE
EXIT leaves the loop at once, while CYCLE skips to the next round of the same loop.
Both are usually paired with an if test, which keeps the loop header simple and the stop rule clear.
program exitdemo
implicit none
integer :: i
do i = 1, 10
if (i == 4) exit
if (i == 2) cycle
print *, i
end do
end program exitdemo
Nested loops
Loops can sit inside other loops to walk over tables, grids, and pairs of values.
Give each level its own counter, and keep the inner body short so the structure stays easy to follow.
program nestdemo
implicit none
integer :: i, j
do i = 1, 3
do j = 1, 2
print *, i, j
end do
end do
end program nestdemo
The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.
Article author: Arthur Isaev