    Next: Application to DO loops: Up: Controlling the flow of Previous: Examples   Contents

## Repetitive action

DO Loops permit repetitive action.

Syntax:

 DO END DO

The loop can be named and the body can contain EXIT or CYCLE statements.

The loop is worked out as follows

1. Evaluate numerical expressions , and, if present, . If not present, is assumed to have the default value = 1.
2. Initialize the Do variable, .
3. The iteration count is computed with the formula

Note that both the number of iterations and the stride are evaluated before execution of the loop begins. Subsequent value changes will have no influence on the iteration process. If the execution cycle starts. At the end of each cycle, the iteration counter is decremented by 1

and the DO variable () is modified by adding the stride

The iteration continues if , otherwise exits. As a consequence, at the end of the iterations, might assume a value different from .

Modifying the inside the body loop is prohibited (and results in a compilation error).

For example, a missing stride is set by default to 1. The code

  do i=1,9
print*, i
end do


will execute the loop exactly 11 times, and will produce the output .

  do i=1,9,2
print*, i
end do


will produce the output .

A negative stride is possible, the code

  do  i=9,1,-2
print*, i
end do


will produce the output .

The loop

  do i=9,1,1
print*, i
end do


will produce no output since initially . Also, the loop

  do i=1,9,-1
print*, i
end do \\

will produce no output since initially .

EXIT statement finishes the innermost loop; however, with named do loops, it can exit the indicated loop, regardless of its nesting level. Similarly, CYCLE outer cycles back to the outer loop, whereas a plain CYCLE would have cycled back to the inner loop.

outer: do i=1,9
inner: do j=i,9
print*, "before: ",i, j
if (j .gt. 3) cycle outer ! go to outer: do
print*, "before: ",i, j
if (j .gt. 6) exit outer ! go to outer: do
print*, "after: ",i,j
end do inner
end do outer    Next: Application to DO loops: Up: Controlling the flow of Previous: Examples   Contents