Download presentation
Presentation is loading. Please wait.
1
Loops
2
Outline of control structures zSequential zDecision (selection) yA. Logical IF yB. Block IF x1. Single alternative IF x2. Double alternative IF x3. Multiple alternative IF zLoops (repetition)
3
Types of loop zA. Interdetminate y1. Entrance controlled xWHILE loops y2. Exit controlled xREPEAT…UNTIL zB. Determinate y1. Counter controlled xDO loops
4
Indeterminate loops zAn indeterminate loop is one that repeats the statements in it’s body some undetermined number of times. zThe number of repetitions is not set before the the loop begins. zThese loops are controlled by a logical expression ywhile num > 0
5
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 Enter a number -5 The sum is: 35 Sentinel value (used only to signal that the loop should end. Not valid data!
6
WHILE Loop Flowchart Prompt for num Read num num >= 0 Add num to sum truefalse Prompt for num Read num
7
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
8
Trace numsum 1. Declare variables ? ? 2. Set sum to 0 0 4. Read num 5 5. Do while num > 0 5.1 add num to sum 5 5.3 read num 7 5.1 add num to sum 12 5.3 read num 23 5.1 add num to sum 35 5.3 read num -5 6. Print sum 35 7. End Sentinel value
9
Example f77 program INTEGER num, sum sum = 0 PRINT*, “This program adds up positive numbers” PRINT*, “A negative number will stop it.” PRINT*, “Enter a number” READ*, num DO WHILE (num.gt. 0) sum = sum + num PRINT*, “Enter a number” READ*, num ENDDO PRINT*, The sum is: “, sum END 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
10
Example sentinel values zDO WHILE (num.ne. -999) zDO WHILE (num.gt. 0) zDO WHILE (num.lt. 0) zDO WHILE (name.ne. ‘Xerxys’) zDO WHILE ((num.gt. 0).and. (num.lt. 100))
11
F90 Example program WHILE structure INTEGER num, sum sum = 0 PRINT*, “This program adds up positive numbers” PRINT*, “A negative number will stop it.” PRINT*, “Enter a number” READ*, num DO if (num.le. 0) EXIT sum = sum + num PRINT*, “Enter a number” READ*, num ENDDO PRINT*, The sum is: “, sum END 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
12
REPEAT loop Flowchart Prompt for num Read num num < 0 Add num to sum truefalse Prompt for num Read num
13
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
14
Trace numsum 1. Declare variables ? ? 2. Set sum to 0 0 4. Read num 5 5. Repeat until num < 0 5.1 add num to sum 5 5.3 read num 7 5.1 add num to sum 12 5.3 read num 23 5.1 add num to sum 35 5.3 read num -5 6. Print sum 35 7. End Sentinel value
15
F90 Example program REPEAT…UNTIL structure INTEGER num, sum sum = 0 PRINT*, “This program adds up positive numbers” PRINT*, “A negative number will stop it.” PRINT*, “Enter a number” READ*, num DO sum = sum + num PRINT*, “Enter a number” READ*, num if (num.le. 0) EXIT ENDDO PRINT*, The sum is: “, sum END 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
16
While vs. repeat loops zWhile loops can be written to accomplish everything that a repeat can do. zRepeat loops ALWAYS process the first data item! zThere are few instances when this is appropriate. Usually you wish to check the data first. zExample of repeat is program to read characters until EOF is encountered.
17
Determinate loops zA determinate loop is one that repeats the statements in it’s body a designated number of times. zThis loop uses a counter to keep track of how many times the body of the loop has repeated itself zWe call a repetition of the body of a loop an ‘iteration’
18
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
19
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
20
Trace numsumin 1. Declare variables???? 2. Set sum to 00 4. Read n3 5. Do n times1 5.2 read num5 5.3 add num to the sum5 5. 2 5.2 read num7 5.3 add num to sum12 5.3 5.2 read num23 5.3 add num to sum35 6. Print sum35 7. End
21
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
22
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
23
General form of f77 DO loop DO K INDEX = INT, LIMIT, INCR label at end of loop index value (loop control variable) test value increment initial value DO 20 i = 1, 10, 2
24
Loop control variables zTraditionally, loop control variables are named i, j, k, l, m or n. zImplicit data typing automatically makes these variables type integer. zImplicit typing means that the variables do not have to be declared. zAll variables should be declared. zTo turn off implicit typing in f90, use IMPLICIT NONE
25
Examples DO 20 i = 1, 10 DO 20 i = 1, 10, 2 DO 20 i = -1, -10, -2 DO 20 i = 1, -10 10 iterations, increments by 1 5 iterations, increments by 2 5 iterations, decrements by -2 0 iterations, increments by 1
26
Tables zA common use of DO loops is to produce tabular output. zEach iteration produces one line in the table.
27
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
28
Celsius to Fahrenheit program output Celsius Fahrenheit 20 68.00000 15 59.00000 10 50.00000 5 41.00000 0 32.00000 -5 23.00000 -10 14.00000 -15 5.00000 -20 -4.00000
29
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
30
Accumulators zAre used to compile sums or count events zMust be initialized before the loop begins zExample yadding up the sum of numbers ymake sure the sum is set to 0 first yaccumulate the sum in the loop
31
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
32
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
33
Counters zAre used to count event occurances zMust be initialized before the loop begins yset counter to 0 zExample yaccumulating each instance of an event
34
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
35
DO loops in reverse zDO loops allow you to increment or decrement the loop control variable during each pass.
36
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
37
Celsius to Fahrenheit program output Celsius Fahrenheit -20 -4.00000 -15 5.00000 -10 14.00000 -5 23.00000 0 32.00000 5 41.00000 10 50.00000 15 59.00000 20 68.00000
38
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
39
WHILE loops vs. DO loops zThe type of loop you use depends on the nature of the tasks to be performed. zCheck your algorithm for the the correct description of the process that is involved. zRules of thumb are given on the next slide
40
Rules of thumb zIf your loop asks for data, and the number of data items entered by the user may vary each time, use a WHILE loop zIf the program knows exactly how many times the loop should execute, use a DO loop zIf 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.
41
A data entry problem Employee Time Card Name: Joe Schmo ID: 12345 Hours: 45 Rate: $7.50 You wish to write a program to help a person enter employee time card data. What approach should you take?
42
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)
43
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
44
Answer The WHILE loop is better. Why?
45
A dehumanizing DO loop Employee Time Card Name: Joe Schmo ID: 12345 Hours: 45 Rate: $7.50 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.
46
General advice zAsking a user to perform a tedious, repetitive task with high error potential before they can run your program is bad program design. zThe reason we have computers is to handle tedious, repetitive tasks and reduce errors. zAlways make the program as simple as possible for the user.
47
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
48
Program trace i j amount sales stores depts set stores to 5 2 set depts to 3 3 do 10 i = 1, stores 1 sales = 0 0 do 20 j = 1, depts 1 read amount 10000.00 add to sales 10000.00 do (j) 2 read amount 25000.00 add to sales 35000.00 do (j) 3 read amount 20000.00 add to sales 55000.00 print sales 55000.00 do (i) 2 sales = 0 0 do 20 j = 1, depts 1 read amount 35000.00 add to sales 35000.00 do (j) 2 read amount 15000.00 add to sales 50000.00
49
Program trace (continued) i j amount sales stores depts do (j) 3 read amount 45000.00 add to sales 95000.00 print sales 95000.00 end
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.