0% found this document useful (0 votes)
52 views26 pages

Computer Science 1510

This document summarizes lecture 9 of CS1510, which discusses repetition in Fortran using DO, DO WHILE, and DO EXIT loops. It provides examples of counter-controlled DO loops, DO WHILE loops, nested loops, and using EXIT and CYCLE statements. Key points covered include the syntax and execution of each loop type as well as ensuring loops terminate to avoid infinite repetition.

Uploaded by

Zhichao Wang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views26 pages

Computer Science 1510

This document summarizes lecture 9 of CS1510, which discusses repetition in Fortran using DO, DO WHILE, and DO EXIT loops. It provides examples of counter-controlled DO loops, DO WHILE loops, nested loops, and using EXIT and CYCLE statements. Key points covered include the syntax and execution of each loop type as well as ensuring loops terminate to avoid infinite repetition.

Uploaded by

Zhichao Wang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Computer Science 1510

Lecture 9

September 26, 2016

Lecture Outline

Repetition:
DO
DO WHILE
DO EXIT

Examples involving selection and repetition

CS1510 Lecture 9
Repetition

With IF and SELECT-CASE statements we saw how


to execute portions of code only if some condition
is satisfied.

On the other hand, in some instances we may want


to execute a section of code many times.

The Fortran construct that can accomplish this


repetition or iteration of statements is called a DO
loop.

The DO loop has 3 different forms:


1. The counter-controlled DO loop which iterates
some specified number of times.
2. The DO WHILE loop which iterates while some
condition is true.
3. The DO EXIT loop which is a generalized version
of a DO WHILE loop.

CS1510 Lecture 9 1
Counter-controlled DO loop
Syntax:
DO control-variable=initial,limit,step-size
statements-to-repeat
END DO

Statements in between DO and END DO, referred to


as the body of the loop, are repeatedly executed.

The integer control-variable is referred to as


the loop counter.

Execution proceeds as follows:


1. Set the value of control-variable to initial.
2. Check to see if control-variable is
limit if step-size > 0, or
limit if step-size < 0.
3. If so, the body of the loop is executed, step-size
is added to control-variable and step 2 is
repeated. Otherwise, repetition terminates.

If not specified, the value of step-size is one.

CS1510 Lecture 9 2
Example 1: DO
PROGRAM Hello
INTEGER::i
DO i=1,10
WRITE(*,*) Hello
END DO
END PROGRAM Hello

The above code prints Hello 10 times.

Execution proceeds as follows:


1. The loop counter i is initialized to 1.
2. Since this value is less than the limit of 10, the
WRITE statement is executed.
3. We go back to the DO statement where i is
increased by one (the default value).
4. This value is less than 10 so the WRITE
statement is executed.
5. This iteration continues up to i=10, when the
WRITE statement is executed for the last time
since i is then increased to 11 which is greater
than 10, ending the loop.
6. Execution moves to the statement following the
END DO.

CS1510 Lecture 9 3
Example 2: DO
PROGRAM Odd
INTEGER::i,n
READ(*,*) n
DO i=1,n,2
WRITE(*,*) i
END DO
END PROGRAM Odd

Prints out the odd numbers less than or equal to n.

The loop counter i is initialized to 1, and is


increased by 2 on each iteration of the loop. The
loop terminates when i is greater than n.

If n is odd, say 7, then i will have the value 1 on


the first iteration of the loop, 3 on the second, 5
on the third, and 7 on the fourth, after which the
loop terminates. Thus, the WRITE statement was
executed 4 times.

If n is even, say 8, then the loop is again executed 4


times, with the same output as above since 7+2=9
(which is >8).

CS1510 Lecture 9 4
Example 3: DO

What is the value of the loop counter at the end of


the loop execution?

For example, if we were to print the value of i after


the loop in the first example:

PROGRAM Hello
INTEGER::i
DO i=1,10
WRITE(*,*) Hello
END DO
WRITE(*,*) i = ,i
END PROGRAM Hello

we would obtain i=11 since the counter is increased


prior to checking if it has exceeded the limit.

CS1510 Lecture 9 5
Example 4: DO

The only restriction on the value of step-size


is that it be nonzero, therefore, we can have
a negative step-size such that the value of
control-variable is decremented.

Repetition continues as long as the value of


control-variable is greater than or equal to
limit.

Example:

PROGRAM Hello
INTEGER::i
DO i=10,1,-1
WRITE(*,*) Hello
END DO
WRITE(*,*) i = ,i
END PROGRAM Hello

Hello would be printed 10 times and the value of


i printed after the loop would be 0.

CS1510 Lecture 9 6
Counter-controlled DO loop

The number of repetitions of a counter-controlled


DO loop is determined prior to the start of repetition.

This number depends on the values of init, limit,


and step-size.

Although the values of variables init, limit, and


step-size can be changed within the body of the
loop, such a change does not affect the number of
repetitions.

Attempting to change the value of the


control-variable within the body of the loop
will result in a compile-time error.

CS1510 Lecture 9 7
Example 5: DO

The initial value, the limit, and the step-size can be


variables or expressions in addition to constants.

Example:

PROGRAM Sum_of_integers
IMPLICIT NONE
INTEGER :: num, i, sum=0
WRITE(*,*) This program prints the sum &
& 1 + 2 + 3 +...+ num
WRITE(*,*) Enter a value for num
READ(*,*) num
DO i=1,num
sum = sum + i
END DO
WRITE(*,*) 1 + 2 + 3 +...+ ,num, = ,sum
END PROGRAM Sum_of_integers

CS1510 Lecture 9 8
Example 6: DO

DO loops can be nested.

Example:

PROGRAM Mult_table
IMPLICIT NONE
INTEGER :: m, n, lastm, lastn, prod
WRITE(*,*) Calculating m*n up to some limit
WRITE(*,*) Enter the limit of m and n
READ(*,*) lastm, lastn
WRITE(*,*) M N M*N
WRITE(*,*) -------------
DO m=1,lastm
DO n=1,lastn
prod = m*n
WRITE(*,2) m,n,prod
END DO
END DO
2 FORMAT(I2,2X,I2,2X,I3)
END PROGRAM Mult_table

CS1510 Lecture 9 9
Fortran statements: DO-WHILE

A DO-WHILE loop combines the iteration of a


DO loop with the conditional execution of an IF
statement.

This is useful when the number of repetitions is not


known in advance.

Syntax:

DO WHILE (logical-expression)
statements-to-repeat
END DO

logical-expression is any expression that


evaluates to true or false.

The loop iterates as long as logical-expression


is true.

CS1510 Lecture 9 10
Example 1: DO WHILE

PROGRAM While
IMPLICIT NONE
INTEGER::n,m
n=0
m=5
DO WHILE((m-n)>0)
n=n+1
WRITE(*,90) m,n
END DO
90 FORMAT(m = ,I2, n = ,I2)
END PROGRAM While

Output:

m = 5 n = 1
m = 5 n = 2
m = 5 n = 3
m = 5 n = 4
m = 5 n = 5

CS1510 Lecture 9 11
Example 2: DO WHILE

PROGRAM While_odd
INTEGER::i,n
i=1
READ(*,*) n
DO WHILE (i<=n)
WRITE(*,*) i
i=i+2
END DO
END PROGRAM While_odd

Like PROGRAM Odd, the above program prints the


odd numbers less than or equal to n, but uses a
DO WHILE loop instead of a counter-controlled DO
loop.

CS1510 Lecture 9 12
Fortran statements: DO EXIT

Syntax:

DO
statement-sequence-1
IF (logical-expression) EXIT
statement-sequence-2
END DO

IF logical-expression is true, the EXIT


command causes the execution to break out of
the loop, that is, execution is immediately moved
to the statement following the END DO.

A DO EXIT loop behaves similar to a DO WHILE


loop in the case where statement-sequence-1 is
not present.

One has to be careful to not introduce an infinite


loop (ie. a loop that never stops iterating)
since termination of a DO EXIT loop requires
logical-expression to be true at some point.

CS1510 Lecture 9 13
Example: DO EXIT

PROGRAM Summation
IMPLICIT NONE
INTEGER :: num, sum, limit

WRITE(*,*) Finding smallest value of n such that &


& 1+2+...+n exceeds limit
WRITE(*,*) Enter value for limit
READ(*,*) limit
num = 0
sum = 0
DO
IF (sum > limit) EXIT
num = num + 1
sum = sum + num
END DO
WRITE(*,*) 1+...+,num,=,sum,>,limit
END PROGRAM Summation

CS1510 Lecture 9 14
Fortran statements: CYCLE

In some cases we may want to terminate the current


iteration of a loop and return to the beginning of
the loop for the next iteration.

This can be accomplished by using a CYCLE


statement.

Syntax:

DO i=1,N
statement-sequence-1
IF (logical-expression-1) CYCLE
statement-sequence-2
END DO

If logical-expression-1 is true on any given


iteration, statement-sequence-2 is skipped, and
execution returns to the top of the loop.

A CYCLE statement can be used in any type of DO


loop.

CS1510 Lecture 9 15
A few more points about loops

The statements within each loop should be indented


for clarity.

It is possible for the body of a loop to never be


executed. For example, in a counter-controlled DO
loop, if initial exceeds limit on the first check,
then control jumps to the statement following the
END DO.

EXIT and CYCLE can also be used in counter-


controlled DO and DO WHILE loops.

CS1510 Lecture 9 16
Program 1: Mean time to failure
PROGRAM Mean_Time_to_Failure
!-----------------------------------------------------------------------
! Program to read a list of failure times, count them, and find the
! mean time to failure. Values are read until an end-of-data flag
! is read. Identifiers used are:
! INPUT:
! A list of failure times (FailureTime = current failure time read)
! OUTPUT:
! NumTimes : the number of failure time readings
! MeanFailureTime : the mean time to failure
!-----------------------------------------------------------------------
IMPLICIT NONE
INTEGER :: NumTimes
REAL :: FailureTime, Sum, MeanFailureTime
REAL, PARAMETER :: EndDataFlag = -1.0
Sum=0.0
NumTimes=0
WRITE(*,*) "Enter failure time of", EndDataFlag, "to stop."

DO
WRITE(*,*) "Enter failure time:"
READ(*,*) FailureTime
! If end-of-data, terminate repetition
IF (FailureTime == EndDataFlag) EXIT
NumTimes = NumTimes + 1
Sum = Sum + FailureTime
END DO
IF (NumTimes /= 0) THEN
MeanFailureTime = Sum / NumTimes
WRITE(*,*)
WRITE(*,*) "Number of failure time readings:", NumTimes
WRITE(*,*) "Mean time to failure:", MeanFailureTime
ELSE
WRITE(*,*) "No failure times were entered."
END IF
END PROGRAM Mean_Time_to_Failure

CS1510 Lecture 9 17
Example 2: Approximating sin(x) and cos(x)

Both the sine and cosine functions are represented


by infinite series:

X

x2n+1 x3 x5 x7
n
sin(x) = (1) = x + +
n=0
(2n + 1)! 3! 5! 7!

X

x 2n
x 2
x 4
x 6
cos(x) = (1)n = 1 + +
n=0
(2n)! 2! 4! 6!

Thus, we can approximate sin(x) or cos(x) for some


x by computing some finite number of terms in the
corresponding sum, call this number of terms n.

The following program approximates the value of


sin(x) using the above sum.

CS1510 Lecture 9 18
Program 2: Approximating sine

PROGRAM Approx_sine
IMPLICIT NONE
INTEGER::i,n
REAL::x,term,approx
WRITE(*,*) Enter a value for x
READ(*,*) x
WRITE(*,*) How many terms would you like to include?
READ(*,*) n
term=x
approx=x
DO i=1,n-1
term=(-1)*term*(x**2/(2*i*(2*i+1)))
approx=approx+term
END DO
WRITE(*,*) sin(,x,) is approximately,approx
END PROGRAM Approx_sine

CS1510 Lecture 9 19
Program 3: Approximating sine/cosine
PROGRAM Functions
IMPLICIT NONE
INTEGER::i,n
REAL::x,term,approx
CHARACTER::func
WRITE(*,*) Enter s for sin, and c for cos or q to quit
READ(*,*) func
DO WHILE(func/=q)
WRITE(*,*) Enter a value for x
READ(*,*) x
WRITE(*,*) How many terms would you like to include?
READ(*,*) n
SELECT CASE (func)
CASE(s)
term=x
approx=x
DO i=1,n-1
term=(-1)*term*(x**2/(2*i*(2*i+1)))
approx=approx+term
END DO
WRITE(*,*) sin(,x,) is approximately,approx
CASE(c)
term=1
approx=1
DO i=1,n-1
term=(-1)*term*(x**2/(2*i*(2*i-1)))
approx=approx+term
END DO
WRITE(*,*) cos(,x,) is approximately,approx
CASE DEFAULT
WRITE(*,*) Invalid entry, try again
END SELECT
WRITE(*,*) Enter s for sin, and c for cos or q to quit
READ(*,*) func
END DO
END PROGRAM Functions

CS1510 Lecture 9 20
Example 3: Euclids algorithm

Suppose that you have two integers m and n, and


you want to find their greatest common divisor
(GCD).

According to Euclids algorithm we do the following.


Taking m = 1976 and n = 1032,

1976 = 1032 1 + 944


1032 = 944 1 + 88
944 = 88 10 + 64
88 = 64 1 + 24
64 = 24 2 + 16
24 = 16 1 + 8
16 = 8 2 + 0

Then the GCD is 8 (the final divisor).

CS1510 Lecture 9 21
Euclids algorithm - Why it works

Suppose that we want to find the GCD of a and b.

We know that a = sd and b = td for some integers


s and t, where d is the GCD.

If we divide a by b we obtain a quotient q and a


remainder r such that a = qb + r.

= r = a qb = sd qtd = (s qt)d

Thus d is also a divisor of r.

Therefore, the GCD of a and b is also the GCD of


b and r.

Since r < b we will eventually obtain r = 0.

CS1510 Lecture 9 22
Program 4: Euclids algorithm

PROGRAM Euclid
IMPLICIT NONE
INTEGER::m,n,q,r
WRITE(*,*) Enter two integers m and n, where m>n
READ(*,*) m,n
r=1
DO WHILE (r/=0)
q=m/n
r=m-q*n
WRITE(*,*) m, = ,n, * ,q, + ,r
m=n
n=r
END DO
WRITE(*,*) The greatest common divisor is ,m
END PROGRAM Euclid

CS1510 Lecture 9 23
Example 4: Linear Least-Squares
Suppose that you have data collected from an
experiment, and you want to compute a line of
best fit.

We want to compute values for the slope m, and


the y-intercept b of a line y = mx + b that in some
way best fits our data (m and b are called regression
coefficients).

In the method of least squares, the best fit is


obtained by minimizing the sum of the squares of
the deviations of the observed y-values from the
predicted y-values,
X
n
[yi (mxi + b)]2
i=1
.
Minimizing this function gives,
P P
( xy) ( x) y
m= P 2 P b = y m
x
( x ) ( x) x

where x
and y are the mean values.

CS1510 Lecture 9 24
Program 5: Linear Least-Squares
PROGRAM Least_Squares_Line
IMPLICIT NONE
INTEGER :: NumPoints
REAL :: X, Y, Sum_of_X, Sum_of_X_squared, Sum_of_Y, Sum_of_XY,&
X_Mean, Y_Mean, Slope, Y_Intercept
REAL, PARAMETER :: EndDataFlag = -99.0

NumPoints = 0
Sum_of_X = 0.0
Sum_of_X_squared = 0.0
Sum_of_Y = 0.0
Sum_of_XY = 0.0
WRITE(*,*) "To stop, enter", EndDataFlag, " for coordinates of point."

DO
WRITE (*, (1X, A), ADVANCE = "NO") "Enter point: "
READ(*,*) X, Y

! If end of data, terminate repetition.


IF ((X == EndDataFlag) .OR. (Y == EndDataFlag)) EXIT

NumPoints = NumPoints + 1
Sum_of_X = Sum_of_X + X
Sum_of_X_squared = Sum_of_X_squared + X ** 2
Sum_of_Y = Sum_of_Y + Y
Sum_of_XY = Sum_of_XY + X * Y
END DO

! Find equation of least-squares line


X_Mean = Sum_of_X / NumPoints
Y_Mean = Sum_of_Y / NumPoints
Slope = (Sum_of_XY - Sum_of_X * Y_Mean) / &
(Sum_of_X_squared - Sum_of_X * X_Mean)
Y_Intercept = Y_Mean - Slope * X_Mean
WRITE(*,*) "Equation of least-squares line is y =", &
Slope, "x +", Y_Intercept
END PROGRAM Least_Squares_Line

CS1510 Lecture 9 25

You might also like