Fortran Do Loop Construct Tutorialspoint
Fortran Do Loop Construct Tutorialspoint
The do loop construct enables a statement, or a series of statements, to be carried out iteratively,
while a given condition is true.
Syntax
The general form of the do loop is −
Where,
the loop variable var should be an integer
start is initial value
stop is the final value
step is the increment, if this is omitted, then the variable var is increased by unity
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
https://www.tutorialspoint.com/fortran/fortran_do_loop.htm 1/4
2/26/2021 Fortran - Do Loop Construct - Tutorialspoint
after the loop. In our case, the condition is that the variable var reaches its final value stop.
After the body of the loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update the loop control variable var.
The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes false, the loop terminates.
Example 1
Live Demo
program printNum
implicit none
! define variables
integer :: n
do n = 11, 20
! printing the value of n
print*, n
end do
https://www.tutorialspoint.com/fortran/fortran_do_loop.htm 2/4
2/26/2021 Fortran - Do Loop Construct - Tutorialspoint
When the above code is compiled and executed, it produces the following result −
11
12
13
14
15
16
17
18
19
20
Example 2
This program calculates the factorials of numbers 1 to 10 −
Live Demo
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
When the above code is compiled and executed, it produces the following result −
1 1
2 2
3 6
4 24
5 120
6 720
https://www.tutorialspoint.com/fortran/fortran_do_loop.htm 3/4
2/26/2021 Fortran - Do Loop Construct - Tutorialspoint
7 5040
8 40320
9 362880
10 3628800
https://www.tutorialspoint.com/fortran/fortran_do_loop.htm 4/4