Control Flow
Do Loop
Counted Iteration
A do i = first, last loop iterates a counter and updates accumulator state.
Program
Play the program to add the numbers 1 through 3.
do_loop.f90
Replay: real traced execution (multi-file project)
program do_loop
implicit none
integer :: i, total
total = 0
do i = 1, 3
total = total + i
end do
print '(I0)', total
end program do_loop
total ← 0
3integer :: i, total4total = 05do i = 1, 3values this step0totali ← 1
4total = 05do i = 1, 36 total = total + ivalues this step1itotal ← 1
5do i = 1, 36 total = total + i7end dovalues this step0 → 1total1ii ← 2
4total = 05do i = 1, 36 total = total + ivalues this step2itotal ← 3
5do i = 1, 36 total = total + i7end dovalues this step1 → 3total2ii ← 3
4total = 05do i = 1, 36 total = total + ivalues this step3itotal ← 6
5do i = 1, 36 total = total + i7end dovalues this step3 → 6total3iprint '(I0)', total
7 end do8 print '(I0)', total9end program do_loopoutput6values this step6total
Add Each Counter
totalstarts at0.- The loop runs with
i = 1, then2, then3. - Each pass adds
iintototal. - The printed total is
6. | Loop valuei| Running total | | --- | --- | |1|1| |2|3| |3|6|
do loop
`do i = 1, 3` iterates with an integer counter.
accumulator
`total` keeps state across iterations.
end do
`end do` marks the loop boundary.
Exercise: do_loop.f90
Use a counted do loop to add 1 through 3 and print the final total