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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With