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 :

label: DO v=il, i2, i3

where

• snum is a statement number from 1 to 99999 which marks the end of the body of the loop in FORTRAN 77 (also called the range of the DO loop)
• label is an optional (but recommended) identifier used in FORTRAN 90 only.
• v the DO variable should be INTEGER. In FORTRAN 77 it may possibly be REAL, although this is not recommended.
• i1 is the initial value of the DO variable and will always be assigned to the DO variable when the DO statement is executed .
• i2 is a limit value used in the trip count calculation to determine the number of times the body is to be repeated.
• i3 is the increment added to the DO variable each time the loop is successfully executed. This parameter may be omitted in which case it assumes a value of 1 by default.
• i2, and i3 can be arithmetic expressions of any complexity.

!

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

Loop Control Construct

A) Simple example: repeat a block 100 times

DO K=1,100

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)

THE TRIP COUNT

C) Computing the trip count :

Trip count = (limit - init + inc)/(inc)

DO K=1,100,2

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

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