Value of Fortran DO loop index after the loop [duplicate]

拥有回忆 提交于 2019-12-24 00:09:47

问题


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).


回答1:


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.




回答2:


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:

  1. 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.



来源:https://stackoverflow.com/questions/18146622/value-of-fortran-do-loop-index-after-the-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!