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
  1. total ← 0

    3integer :: i, total4total = 05do i = 1, 3
    values this step0total
  2. i ← 1

    4total = 05do i = 1, 36    total = total + i
    values this step1i
  3. total ← 1

    5do i = 1, 36    total = total + i7end do
    values this step0 1total1i
  4. i ← 2

    4total = 05do i = 1, 36    total = total + i
    values this step2i
  5. total ← 3

    5do i = 1, 36    total = total + i7end do
    values this step1 3total2i
  6. i ← 3

    4total = 05do i = 1, 36    total = total + i
    values this step3i
  7. total ← 6

    5do i = 1, 36    total = total + i7end do
    values this step3 6total3i
  8. print '(I0)', total

    7    end do8    print '(I0)', total9end program do_loop
    output6
    values this step6total

Add Each Counter

  1. total starts at 0.
  2. The loop runs with i = 1, then 2, then 3.
  3. Each pass adds i into total.
  4. The printed total is 6. | Loop value i | 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