do迴圈結構使得一個語句或一系列語句,以進行迭代,當一個給定的條件為真。
語法
do迴圈的一般形式是:
do var = start, stop [,step] ! statement(s) … end do
這裏,
- 迴圈變數var應該是一個整數
- start 是初始值
- stop 是最終值
- 步驟step是遞增,如果此被省略,則變數var以單位增加
例如:
! compute factorials do n = 1, 10 nfact = nfact * n ! printing the value of n and its factorial print*, n, " ", nfact end do
流程圖
這裏是控制 do 迴圈結構的流程:
-
初始步驟首先被執行,並且僅一次。這一步可以聲明和初始化任何迴圈控制變數。在我們的例子中,變數var被初始化開始的值。
-
接下來,計算條件。如果為true,則執行循環體。如果是假,則循環體不執行,只是在迴圈之後流量控制跳轉到下一個語句。在我們的情況下,該條件就是在變數var達到其最終值stop。
-
所述循環體執行後,控制流跳轉回至increment 語句。這個語句可以更新迴圈控制變數var。
-
條件現在重新評估。如果為true,迴圈執行的過程重複(循環體,再遞增一步,然後再條件)。直到條件為假,迴圈終止。

示例 1
這個例子將輸出數字11到20:
program printNum implicit none ! define variables integer :: n do n = 11, 20 ! printing the value of n print*, n end do end program printNum
讓我們編譯和運行上面的程式,這將產生以下結果:
11 12 13 14 15 16 17 18 19 20
實例 2
這個程式計算數字1到10的階乘:
program factorial implicit none ! define variables integer :: nfact = 1 integer :: n ! compute factorials do n = 1, 10 nfact = nfact * n ! print values print*, n, " ", nfact end do end program factorial
讓我們編譯和運行上面的程式,這將產生以下結果:
1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 40320 9 362880 10 3628800
上一篇:
Fortran迴圈
下一篇:
Fortran do...while迴圈結構