This question already has an answer here:
-
Why is the Fortran DO loop index larger than the upper bound after the loop?
2 answers
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 to 11
before the do
loop determines that it must terminate. The value of 11
is the first value of i
which causes the end condition of 1
..10
to fail. So when the loop is done, the value of i
is 11
.
Put into pseudo-code form:
1) i <- 1
2) if i > 10 goto 6
3) ...code...
4) i <- i + 1
5) goto 2
6) print i
When it gets to step 6, the value of i
is 11
. When you put in your if
statement, it becomes:
1) i <- 1
2) if i > 10 goto 7
3) ...code...
4) if i = 7 goto 7
5) i <- i + 1
6) goto 2
7) print i
So clearly i
will be 7
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
[ , ] do-variable = scalar-numeric-expr1 , scalar-numeric-expr2 [ , scalar-numeric-expr3 ]
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
MAX(INT((m2 –m1+m3)/m3),0)
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.