Do Loops
by
gg582 · 2026-10-29 07:39:10 · 12 views · 3 min read
Table of contents
Basic Do Loops
Fortran uses do loops instead of C-style for loops.
This is a minimal example to show "Do Loops".
program do_counter
implicit none
integer :: i
print *, "i -> 1..5"
do i = 1, 5
print *, i
end do
print *, "i -> 10..8..0"
do i = 10, 0, -2
print *, i
end do
end program do_counter
Let's see the result.
i -> 1..5
1
2
3
4
5
i -> 10..8..0
10
8
6
4
2
0
So basically, these two blocks are the same.
do i = 1, 5
print *, i
end do
do i = 1, 5, 1
print *, i
end do
This means Fortran 2018 implicitly assumes the third argument of do loops to be 1.
While Loops
program while_loops
implicit none
integer :: n = 1
do while (n < 5)
print *, "while n =", n
n = n + 1
end do
n = 1
do
if (n >= 5) exit
print *, "while n =", n
n = n + 1
end do
end program while_loops
exit breaks out of a loop.
Those two loops print the same output.
while n = 1
while n = 2
while n = 3
while n = 4
When a condition is complex enough, you can use if branches to break out of a loop.
But when the condition is simple enough to use do while, don't use if branches.
Then, how can you continue to the next cycle without executing the remaining statements?
program loop_control
implicit none
integer :: i
do i = 1, 10
! Continue and skip to the next cycle when i is even
if (mod(i, 2) == 0) cycle
! Exit the loop when i is greater than 7
if (i > 7) exit
print *, "Odd number:", i
end do
! Print 1, skip 2, print 3, skip 4, print 5, skip 6, print 7
! The result is 1, 3, 5, 7
end program loop_control
When i is even, it continues to the next cycle. As a result, print function is not executed since the cycle was skipped.
When i is bigger than 7, exit procedure breaks the loop.
However, when
iis 8exitis not executed since its location is belowcycle.
As a result, when i is 9, comparison i > 7 is interpreted as 9 > 7.
9 is bigger than 7. This expression is true. The program executes
exitprocedure.