This question already has an answer here:
How do DO loops work exactly?
Let's say you have the following loop:
do i=1,10
...code...
end do
write(*,*)I
why is the printed I 11, and not 10?
But when the loop stops due to an
if(something) exit
the I is as expected (for example i=7, exit because some other value reached it's limit).
The value of
i
goes to11
before thedo
loop determines that it must terminate. The value of11
is the first value ofi
which causes the end condition of1
..10
to fail. So when the loop is done, the value ofi
is11
.Put into pseudo-code form:
When it gets to step 6, the value of
i
is11
. When you put in yourif
statement, it becomes:So clearly
i
will be7
in this case.I want to emphasize that it is an iteration count that controls the number of times the range of the loop is executed. Please refer to Page 98-99 "Fortran 90 ISO/IEC 1539 : 1991 (E)" for more details.
The following steps are performed in sequence:
Loop initiation:
1.1 if loop-control is
1.1.1 The initial parameter m1, the terminal parameter m2, and the incrementation parameter m3 are established by evaluating scalar-numeric-expr1, scalar-numeric-expr2, and scalar-numeric-expr3, respectively,
1.1.2 The do-variable becomes defined with the value of the initial parameter m1.
1.1.3 The iteration count is established and is the value of the expression
1.2 If loop-control is omitted, no iteration count is calculated.
1.3 At the completion of the execution of the DO statement, the execution cycle begins.
2.The execution cycle. The execution cycle of a DO construct consists of the following steps performed in sequence repeatedly until termination:
2.1 The iteration count, if any, is tested. If the iteration count is zero, the loop terminates
2.2 If the iteration count is nonzero, the range of the loop is executed.
2.3 The iteration count, if any, is decremented by one. The DO variable, if any, is incremented by the value of the incrementation parameter m3.