目录

do循环

do循环结构允许迭代地执行语句或一系列语句,而给定条件为真。

语法 (Syntax)

do循环的一般形式是 -

do var = start, stop [,step]    
   ! statement(s)
   …
end do

Where,

  • 循环变量var应该是一个整数

  • start是初始值

  • stop是最终值

  • step是增量,如果省略,则变量var增加1

例如 (For example)

! compute factorials
do n = 1, 10
   nfact = nfact * n  
   ! printing the value of n and its factorial
   print*,  n, " ", nfact   
end do

流程图 (Flow Diagram)

以下是do循环结构的控制流程 -

  • 首先执行初始步骤,并且仅执行一次。 此步骤允许您声明和初始化任何循环控制变量。 在我们的例子中,变量var用值start初始化。

  • 接下来,评估条件。 如果为真,则执行循环体。 如果为false,则循环体不会执行,控制流会在循环之后跳转到下一个语句。 在我们的例子中,条件是变量var达到其最终值stop。

  • 在循环体执行之后,控制流跳回到增量语句。 此语句允许您更新循环控制变量var。

  • 现在再次评估该条件。 如果为真,则循环执行并且过程自身重复(循环体,然后递增步骤,然后再次调节)。 条件变为false后,循环终止。

做循环

例子1 (Example 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 (Example 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
↑回到顶部↑
WIKI教程 @2018