Lesson 7 - Learning Goals
7.1 How to repeat a section of program
7.2 How use the DO Statement
7.3 Loop Control Construct
7.4 What is the Trip-count and how to calculate it
7.5 How to use the WHILE Statement
LOOPS AND FORMAT
DO LOOP - General form :
where
!
PROGRAM P42
!
!
IMPLICIT NONE
INTEGER :: KS,LT,I,J
PRINT *, 'This is Program >> P42 - Nested DO loops'
!
! Two nested DO loops
KS=0
LT=0
L1: DO I=1,20,2
L2: DO J=I,25
KS=KS+J
END DO L2
LT=LT+I
PRINT *,I,KS,LT
END DO L1
STOP
END PROGRAM P42
A) Simple example: repeat
a block 100 times
DO K=1,100
READ *,A,B,C
SEMI = (A+B+C)/2.0
PRINT *,A,B,C,SEMI
END DO
B) General form:
DO var = init, limit, inc
.
.
.
END DO
var = variable (INTEGER , can be REAL in FORTRAN 77)
init = initial value (INTEGER , can be REAL in FORTRAN 77)
limit = limit value (INTEGER , can be REAL in FORTRAN 77)
inc = increment value (expressions)
C) Computing the trip count
:
Trip count = (limit - init +
inc)/(inc)
DO K=1,100,2
READ *,A,B,C
SEMI = (A+B+C)/2.0
PRINT *,A,B,C,SEMI
END DO
D) Be careful with real
numbers ( ONLY VALID WITH FORTRAN 77 ) :
SUM = 0.0
DO X=0.0, 1.0, 0.1
SUM = SUM + X
PRINT *,X,SUM
END DO
This brings out some special
cases. If for some reason the following loop was programmed
READ *,N
DO 33 K=11,N
33 N=N+K
PRINT *,N
and by mistake the value of N
read in was less than 11, then the trip count for this loop would
be set to zero. If N has a value of 7, the statement labelled
33 is not executed and the PRINT statement will output the original
value of N, namely 7.
A flowchart for the organization
of a FORTRAN 77 DO loop is shown in the next diagram. A few further
examples show that the DO statement itself can be quite complex.
Initialize DO variable
Calculate trip count
Is TRIP COUNT =0?
if YES => exit the loop
if NO => Execute body of DO loop
Decrement trip count
Increment DO variable
Calculate trip count again and same process ...
Go back to lecture menu
Go back to main page