Computers in Engineering - 308-208 Lecture 7
Computers in Engineering - 308-208

# Lesson 7 - Learning Goals

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

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

1. Initialize DO variable
2. Calculate trip count
3. Is TRIP COUNT =0?
• if YES => exit the loop
• if NO => Execute body of DO loop

4. Decrement trip count
5. Increment DO variable
6. Calculate trip count again and same process ...

On to the next lecture
Go back to lecture menu