Transcript Document

Loops
Outline of control structures
 Sequential
 Decision (selection)
A. Logical IF
B. Block IF
1. Single alternative IF
2. Double alternative IF
3. Multiple alternative IF
 Loops (repetition)
Types of loop
A. Interdetminate
1. Entrance controlled
WHILE loops
2. Exit controlled
REPEAT…UNTIL
B. Determinate
1. Counter controlled
DO loops
Indeterminate loops
An indeterminate loop is one that repeats
the statements in it’s body some
undetermined number of times.
The number of repetitions is not set
before the the loop begins.
These loops are controlled by a logical
expression
while num > 0
Example program session
This program adds up positive numbers
A negative number will stop it.
Enter a number
5
Enter a number
7
Enter a number
23
Sentinel value
Enter a number
(used only to signal
-5
that the loop should
The sum is: 35
end. Not valid data!
WHILE Loop
Flowchart
Prompt for num
Read num
true
Add num to sum
Prompt for num
Read num
num
>= 0
false
Algorithm
1. Declare variables
2. Set sum to 0
3. Prompt for num
4. Read num
5. Do while num > 0
5.1 add num to sum
5.2 prompt for next num
5.3 read num
6. Print sum
7. End
Trace
1. Declare variables
2. Set sum to 0
4. Read num
5. Do while num > 0
5.1 add num to sum
5.3 read num
5.1 add num to sum
5.3 read num
5.1 add num to sum
5.3 read num
6. Print sum
7. End
Sentinel value
num
?
5
7
23
-5
sum
?
0
5
12
35
35
Example f77 program
1. Declare variables
2. Set sum to 0
3. Prompt for num
INTEGER num, sum
sum = 0
PRINT*, “This program adds up positive numbers”
PRINT*, “A negative number will stop it.”
PRINT*, “Enter a number”
4. Read num
READ*, num
5. Do while num > 0
DO WHILE (num .gt. 0)
5.1 add num to sum
sum = sum + num
5.2 prompt for next num
PRINT*, “Enter a number”
5.3 read num
READ*, num
ENDDO
6. Print sum
PRINT*, The sum is: “, sum
7. End
END
Example sentinel values
DO
DO
DO
DO
DO
WHILE
WHILE
WHILE
WHILE
WHILE
(num .ne. -999)
(num .gt. 0)
(num .lt. 0)
(name .ne. ‘Xerxys’)
((num .gt. 0) .and. (num .lt. 100))
F90 Example program
WHILE structure
1. Declare variables
2. Set sum to 0
3. Prompt for num
INTEGER num, sum
sum = 0
PRINT*, “This program adds up positive numbers”
PRINT*, “A negative number will stop it.”
PRINT*, “Enter a number”
4. Read num
READ*, num
5. Do while num > 0
DO
if (num .le. 0) EXIT
5.1 add num to sum
sum = sum + num
5.2 prompt for next num
PRINT*, “Enter a number”
5.3 read num
READ*, num
ENDDO
6. Print sum
PRINT*, The sum is: “, sum
7. End
END
REPEAT loop
Flowchart
Prompt for num
Read num
Add num to sum
Prompt for num
Read num
true
num
<0
false
Algorithm: repeat…until
1. Declare variables
2. Set sum to 0
3. Prompt for num
4. Read num
5. Repeat until num < 0
5.1 add num to sum
5.2 prompt for next num
5.3 read num
6. Print sum
7. End
Trace
1. Declare variables
2. Set sum to 0
4. Read num
5. Repeat until num < 0
5.1 add num to sum
5.3 read num
5.1 add num to sum
5.3 read num
5.1 add num to sum
5.3 read num
6. Print sum
7. End
Sentinel value
num
?
5
7
23
-5
sum
?
0
5
12
35
35
F90 Example program
REPEAT…UNTIL structure
1. Declare variables
2. Set sum to 0
3. Prompt for num
INTEGER num, sum
sum = 0
PRINT*, “This program adds up positive numbers”
PRINT*, “A negative number will stop it.”
PRINT*, “Enter a number”
4. Read num
READ*, num
5. Repeat until num < 0
DO
5.1 add num to sum
sum = sum + num
5.2 prompt for next num
PRINT*, “Enter a number”
5.3 read num
READ*, num
if (num .le. 0) EXIT
ENDDO
6. Print sum
PRINT*, The sum is: “, sum
7. End
END
While vs. repeat loops
While loops can be written to accomplish
everything that a repeat can do.
Repeat loops ALWAYS process the first
data item!
There are few instances when this is
appropriate. Usually you wish to check
the data first.
Example of repeat is program to read
characters until EOF is encountered.
Determinate loops
A determinate loop is one that repeats the
statements in it’s body a designated
number of times.
This loop uses a counter to keep track of
how many times the body of the loop has
repeated itself
We call a repetition of the body of a loop
an ‘iteration’
Example program session
This program adds up positive numbers
How many numbers will you enter?
3
Enter a number
5
Enter a number
7
Enter a number
23
The sum is: 35
Algorithm
1. Declare variables
2. Set sum to 0
3. Prompt for n
4. Read n
5. Do n times
5.1 prompt for num
5.2 read num
5.3 add num to the sum
6. Print sum
7. End
Trace
1. Declare variables
2. Set sum to 0
4. Read n
5. Do n times
5.2 read num
5.3 add num to the sum
5.
5.2 read num
5.3 add num to sum
5.
5.2 read num
5.3 add num to sum
6. Print sum
7. End
num
?
5
7
23
sum
?
0
i
?
1
5
12
35
35
2
3
n
?
3
Algorithm
1. Declare variables
2. Set sum to 0
3. Prompt for n
4. Read n
5. Do n times
5.1 prompt for num
5.2 read num
5.3 add num to the sum
6. Print sum
7. End
INTEGER n, sum, num, i
sum = 0
PRINT*, “How many numbers will you enter?”
READ*, n
DO 10 i = 1, n
PRINT*, “Enter a number”
READ*, num
sum = sum + num
10 CONTINUE
PRINT*, “The sum is”, sum
END
Comparing f77 to f90
INTEGER n, sum, num, i
sum = 0
PRINT*, “How many numbers?”
READ*, n
DO 10 i = 1, n
PRINT*, “Enter a number”
READ*, num
sum = sum + num
10 CONTINUE
PRINT*, “The sum is”, sum
END
INTEGER :: n, sum, num, i
sum = 0
PRINT*, “How many numbers?”
READ*, n
DO i = 1, n
PRINT*, “Enter a number”
READ*, num
sum = sum + num
END DO
PRINT*, “The sum is”, sum
END
General form of f77 DO loop
DO K INDEX = INT, LIMIT, INCR
label at end
of loop
initial value
index value
(loop
control
variable)
DO 20 i = 1, 10, 2
test value
increment
Loop control variables
Traditionally, loop control variables are
named i, j, k, l, m or n.
Implicit data typing automatically makes
these variables type integer.
Implicit typing means that the variables
do not have to be declared.
All variables should be declared.
To turn off implicit typing in f90, use
IMPLICIT NONE
Examples
DO 20 i = 1, 10
10 iterations, increments by 1
DO 20 i = 1, 10, 2
5 iterations, increments by 2
DO 20 i = -1, -10, -2
5 iterations, decrements by -2
DO 20 i = 1, -10
0 iterations, increments by 1
Tables
A common use of DO loops is to produce
tabular output.
Each iteration produces one line in the
table.
Converting Celsius to
Fahrenheit
c conversion of Celsius to Fahrenheit temperature
c
INTEGER cbegin, climit, cstep
PARAMETER (cbegin = 20, climit -20, cstep = -5)
INTEGER celsius
REAL fahren
c
c Print the table heading
PRINT*, ‘
Celsius
Fahrenheit’
c
c Print table
DO 10 celsius = cbegin, climit, cstep
fahren = 1.8 * celsius + 32.0
PRINT*, celsius, ‘
‘, fahren
10 CONTINUE
END
Celsius to Fahrenheit
program output
Celsius
20
15
10
5
0
-5
-10
-15
-20
Fahrenheit
68.00000
59.00000
50.00000
41.00000
32.00000
23.00000
14.00000
5.00000
-4.00000
Example: table of squares
c print a list of integers and their squares
c
INTEGER I, square, maxi
c
c Read upper bound
PRINT*, ‘Enter the maximum number’
READ*, maxi
c
c print table of squares
PRINT*, ‘
I
I*I’
DO 20 i = 1, maxi
square = i * i
PRINT*, i, square
20 CONTINUE
END
Accumulators
Are used to compile sums or count events
Must be initialized before the loop begins
Example
adding up the sum of numbers
make sure the sum is set to 0 first
accumulate the sum in the loop
Example: accumulating
c Summation of integers
c
INTEGER num, i, sum
c
c Add up the sum
sum = 0
DO 15 i = 1, 10
READ*, num
sum = sum + num
15 CONTINUE
PRINT*, ‘The sum is ‘, sum
END
Example: computing the
sum of odd integers
c Summation of odd integers
c
INTEGER n, odd, sum
c
c Read upper bound
PRINT*, ‘This program adds up the sum of odd integers’
PRINT*, ‘between 1 and the next number you enter.’
PRINT*, ‘Enter the number’
READ*, n
c
c Add up the sum
sum = 0
DO 10 odd = 1, n, 2
sum = sum + odd
10 CONTINUE
PRINT*, ‘The sum is ‘, sum
END
Counters
Are used to count event occurances
Must be initialized before the loop begins
set counter to 0
Example
accumulating each instance of an event
Example: counting
c Counting even integers
c
INTEGER num, i, count
c
c counting loop
count = 0
DO 15 i = 1, 10
READ*, num
IF (MOD(num,2) .eq. 0) count = count + 1
15 CONTINUE
PRINT*, ‘There were ‘, count, ‘even numbers’
END
DO loops in reverse
DO loops allow you to increment or
decrement the loop control variable during
each pass.
Converting Celsius to
Fahrenheit
c conversion of Celsius to Fahrenheit temperature
c
INTEGER cbegin, climit, cstep
PARAMETER (cbegin = -20, climit 20, cstep = 5)
INTEGER celsius
REAL fahren
c
c Print the table heading
PRINT*, ‘
Celsius
Fahrenheit’
c
c Print table
DO 10 celsius = cbegin, climit, cstep
fahren = 1.8 * celsius + 32.0
PRINT*, celsius, ‘
‘, fahren
10 CONTINUE
END
Celsius to Fahrenheit
program output
Celsius
-20
-15
-10
-5
0
5
10
15
20
Fahrenheit
-4.00000
5.00000
14.00000
23.00000
32.00000
41.00000
50.00000
59.00000
68.00000
Converting DO to WHILE
INTEGER n, sum, num, i
sum = 0
PRINT*, “How many numbers?”
READ*, n
DO 10 i = 1, n
PRINT*, “Enter a number”
READ*, num
sum = sum + num
10 CONTINUE
PRINT*, “The sum is”, sum
END
INTEGER n, sum, num, i
sum = 0
PRINT*, “How many numbers?”
READ*, n
i=1
DO WHILE (i .le. n)
PRINT*, “Enter a number”
READ*, num
sum = sum + num
i=i+1
END DO
PRINT*, “The sum is”, sum
END
WHILE loops vs. DO loops
The type of loop you use depends on the
nature of the tasks to be performed.
Check your algorithm for the the correct
description of the process that is involved.
Rules of thumb are given on the next
slide
Rules of thumb
If your loop asks for data, and the number of
data items entered by the user may vary each
time, use a WHILE loop
If the program knows exactly how many times
the loop should execute, use a DO loop
If you intend on asking the user how many
times the loop should execute, ask the user
for this number only if it is reasonablly small.
A data entry problem
You wish to write a program to help a person enter employee
time card data. What approach should you take?
Employee Time Card
Name: Joe Schmo
ID: 12345
Hours: 45
Rate: $7.50
Approach #1
How many time cards do you have?
35
Enter employee id, hours and rate.
12345, 45, 7.50
Enter employee id, hours and rate.
.
.
.
(this continues 35 times)
Approach #2
Enter employee id, hours and rate. (to end enter negative values)
12345, 45, 7.50
Enter employee id, hours and rate.
.
.
.
(this continues until sentinel values entered)
.
.
.
Enter employee id, hours and rate.
-99999,-99,-9.99
Answer
The WHILE loop is better.
Why?
A dehumanizing DO loop
If you undercount by 1, the program continues after all data has
been entered. If you overcount by 1 the program ends prematurely.
It forces the user to become a slave to the process.
Employee Time Card
Name: Joe Schmo
ID: 12345
Hours: 45
Rate: $7.50
General advice
Asking a user to perform a tedious,
repetitive task with high error potential
before they can run your program is bad
program design.
The reason we have computers is to
handle tedious, repetitive tasks and
reduce errors.
Always make the program as simple as
possible for the user.
Nested loops
INTEGER stores, depts, sales, amount, i, j
stores = 2
depts = 3
DO 10 i = 1, stores
sales = 0
DO 20 j = 1, depts
PRINT*, “Enter dept “, j, “sales for store “, i
READ*, amount
sales = sales + amount
20
CONTINUE
PRINT*, “Total sales for store “, i, “are $”, sales
10 CONTINUE
END
Program trace
set stores to 5
set depts to 3
do 10 i = 1, stores
sales = 0
do 20 j = 1, depts
read amount
add to sales
do (j)
read amount
add to sales
do (j)
read amount
add to sales
print sales
do (i)
sales = 0
do 20 j = 1, depts
read amount
add to sales
do (j)
read amount
add to sales
i
j
amount
1
1
2
3
0
10000.00
25000.00
20000.00
2
1
2
sales
10000.00
35000.00
55000.00
55000.00
0
35000.00
15000.00
35000.00
50000.00
stores
2
depts
3
Program trace (continued)
do (j)
read amount
add to sales
print sales
end
i
j
3
amount
45000.00
sales
95000.00
95000.00
stores
depts