Chapter 5 Repetition and Loop Statements Dr J

  • Slides: 61
Download presentation
Chapter 5 Repetition and Loop Statements Dr. J. -Y. Pan Dept. Comm. Eng. Nat.

Chapter 5 Repetition and Loop Statements Dr. J. -Y. Pan Dept. Comm. Eng. Nat. Chung Cheng Univ. http: //ant. comm. ccu. edu. tw jypan@comm. ccu. edu. tw Copyright © 2004 Pearson Addison-Wesley. All rights reserved. 1 -

5. 1 Repetition in programs v Loop ²A control structure that repeats a group

5. 1 Repetition in programs v Loop ²A control structure that repeats a group of steps in a program v Loop body ²The statements that are repeated in the loop v Three questions to determine whether loops will be required in the general algorithm: (Figure 5. 1) ² 1. Were there any steps I repeated as I solved the problem? If so, which ones? ² 2. If the answer to question 1 is yes, did I know in advance how many times to repeat the steps? ² 3. If the answer to question 2 is no, how did I know how long to keep repeating the steps? 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 2

Figure 5. 1 Flow Diagram of Loop Choice Process 中正大學通訊 程系 潘仁義老師 Advanced Network

Figure 5. 1 Flow Diagram of Loop Choice Process 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 3

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 4

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 4

The while statement: while (bool-expr) statement ; while (bool-expr) { stmts; } (1)First evaluates

The while statement: while (bool-expr) statement ; while (bool-expr) { stmts; } (1)First evaluates bool-expr; (2)If bool-expr’s value is TRUE, it executes stmts, and back to step 1. (3)If bool-expr’s value is FALSE, it terminates. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 5

5. 2 Counting Loops and the while Statement v. Counter-controlled loop (counting loop) ²A

5. 2 Counting Loops and the while Statement v. Counter-controlled loop (counting loop) ²A loop whose required number of iterations can be determined before loop execution begins v. Figure 5. 2 shows a program fragment that computes and displays the gross pay for seven employees. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 6

Figure 5. 2 Program Fragment with a Loop 中正大學通訊 程系 潘仁義老師 Advanced Network Technology

Figure 5. 2 Program Fragment with a Loop 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 7

Figure 5. 3 Flowchart for a while Loop 中正大學通訊 程系 潘仁義老師 Advanced Network Technology

Figure 5. 3 Flowchart for a while Loop 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 8

5. 2 (cont) Counting Loops and the while Statement v. Loop repetition condition ²The

5. 2 (cont) Counting Loops and the while Statement v. Loop repetition condition ²The condition that controls loop repetition v. Loop control variable ²The variable whose value controls loop repetition v. The loop control variable must be ²Initialization ²Testing ²Updating 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 9

5. 3 Computing a Sum or a Product in a Loop vaccumulator ²a variable

5. 3 Computing a Sum or a Product in a Loop vaccumulator ²a variable used to store a value being computed in increments during the execution of a loop v. Fig. 5. 4 Program to Compute Company Payroll 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 10

Figure 5. 4 Program to Compute Company Payroll 中正大學通訊 程系 潘仁義老師 Advanced Network Technology

Figure 5. 4 Program to Compute Company Payroll 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 11

Figure 5. 4 Program to Compute Company Payroll (cont’d) 跑個 GDB? 中正大學通訊 程系 潘仁義老師

Figure 5. 4 Program to Compute Company Payroll (cont’d) 跑個 GDB? 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 12

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 13

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 13

5. 3 (cont) Compound Assignment Operators v. Assignment statements of the form ²variable =

5. 3 (cont) Compound Assignment Operators v. Assignment statements of the form ²variable = variable op expression ²variable op = expression v如 += -= /= %= /= 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 14

5. 4 The for Statement v. Three loop control components ² Initialization of the

5. 4 The for Statement v. Three loop control components ² Initialization of the loop variable ² Test of the loop repetition condition ²Change (update) of the loop control variable v. Using a for statement in a counting loop. (Figure 5. 5) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 15

Figure 5. 5 Using a for Statement in a Counting Loop 中正大學通訊 程系 潘仁義老師

Figure 5. 5 Using a for Statement in a Counting Loop 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 16

The for statement v The for (loop) statement for (init expr; loop condition; step

The for statement v The for (loop) statement for (init expr; loop condition; step expr) { stmts; } Initial expression Step expression Loop condition Yes No statements 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 17

An Example #include <stdio. h> int main(void) { int i, N; printf(“How many =

An Example #include <stdio. h> int main(void) { int i, N; printf(“How many = ? ”); scanf (“%d”, &N); /* Display N asterisks */ for (i = 0; i < N; i += 1) printf(“*”); } // 跑個 GDB吧… 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 18

Increment and decrement operators v. The counting loops that you have seen have all

Increment and decrement operators v. The counting loops that you have seen have all included assignment expressions of form counter = counter +1 or counter +=1 for (counter =0; counter<limit; ++counter) ……. . Side effect a change in the value of a variable as a result of carrying out an operation 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 19

Figure 5. 6 Comparison of Prefix and Postfix Increments 中正大學通訊 程系 潘仁義老師 Advanced Network

Figure 5. 6 Comparison of Prefix and Postfix Increments 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 20

Conditional loops v In many programming situations, you will not be able to determine

Conditional loops v In many programming situations, you will not be able to determine the exact number of loop repetitions before loop execution begins. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 21

5. 5 (cont) Example 5. 5 (Figure 5. 9) v. The program is designed

5. 5 (cont) Example 5. 5 (Figure 5. 9) v. The program is designed to assist in monitoring the gasoline supply in a storage tank at the Super Oil Company refinery. v. The program is to alert the supervisor when the supply of gasoline in the tank falls below 10% of the tank’s 80, 000 barrel storage capacity. v. The barrel used in the petroleum industry equals 42 U. S. gallons 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 22

Figure 5. 9 Program to Monitor Gasoline Storage Tank 中正大學通訊 程系 潘仁義老師 Advanced Network

Figure 5. 9 Program to Monitor Gasoline Storage Tank 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 23

Figure 5. 9 Program to Monitor Gasoline Storage Tank (cont’d) 中正大學通訊 程系 潘仁義老師 Advanced

Figure 5. 9 Program to Monitor Gasoline Storage Tank (cont’d) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 24

Figure 5. 9 Program to Monitor Gasoline Storage Tank (cont’d) 中正大學通訊 程系 潘仁義老師 Advanced

Figure 5. 9 Program to Monitor Gasoline Storage Tank (cont’d) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 25

5. 5 (cont) Example 5. 5 (Figure 5. 9) v. There are three critical

5. 5 (cont) Example 5. 5 (Figure 5. 9) v. There are three critical steps in Fig. 5. 9 that involve the loop control variable current: ²current is initialized to the starting supply in the for statement initialization expression ²current is tested before each execution of the loop body ²current is updated (by subtraction of the amount removed) during each iteration 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 26

Loop design… An example on Ex 5. 5 (Fig 5. 9) Fig 5. 1

Loop design… An example on Ex 5. 5 (Fig 5. 9) Fig 5. 1 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 27

Loop design Sentinel-Controlled Loops v. A loop that process data until the sentinel value

Loop design Sentinel-Controlled Loops v. A loop that process data until the sentinel value is entered has the form ²get a line of data (initialization) ²while the sentinel value has not been encountered (a loop repetition condition) ²process the data line. ²get another line of data (update) Sentinel value An end marker that follows the last item in a list of data 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 28

5. 6 (cont) Example 5. 6 (Figure 5. 10) v. A program that calculates

5. 6 (cont) Example 5. 6 (Figure 5. 10) v. A program that calculates the sum of a collection of exam scores is a candidate for using a sentinel value. v. Sentinel loop 1. Initialize sum to zero 2. Get first score 3. while score is not the sentinel 4. Add score to sum 5. Get next score 有兩次Get 會很怪嗎? 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 29

Figure 5. 10 Sentinel-Controlled while Loop 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 30

Figure 5. 10 Sentinel-Controlled while Loop 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 30

5. 6 (cont) Using a for Statement to Implement a Sentinel Loop v The

5. 6 (cont) Using a for Statement to Implement a Sentinel Loop v The for statement form of the while loop in Fig. 5. 10 /* Accumulate sum of all scores */ printf(“Enter first score (or %d to quit)>”, SENTINEL); for (scanf(“%d”, &score); score != SENTINEL; scanf(“%d”, &score)) { sum += score; printf(“Enter next score(%d to quit)>”, SENTINEL); } 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 31

Endfile-controlled loops v. Here is the pseudo code for an endfilecontrolled loop: ²get the

Endfile-controlled loops v. Here is the pseudo code for an endfilecontrolled loop: ²get the first data value and save input status ²while input status does not indicate that end of file has been reached vprocess data value vget next data value and save input status 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 32

Result value of scanf and fscanf input_status = scanf(“%d%d%lf”, &a, &b, &c); vnumber of

Result value of scanf and fscanf input_status = scanf(“%d%d%lf”, &a, &b, &c); vnumber of data items it actually obtained vnumber of data before encountering error v. EOF: when detecting the endfile before get (End of File) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 33

Figure 5. 11 Batch Version of Sum of Exam Scores Program 中正大學通訊 程系 潘仁義老師

Figure 5. 11 Batch Version of Sum of Exam Scores Program 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 34

Nested loop v. If a for loop is nested inside another for loop, the

Nested loop v. If a for loop is nested inside another for loop, the inner for loop is executed once for each iteration of the outer for loop v. Each for loop must have its own (distinct) index variables so that the variables do not interfere with each other You CANNOT use the same variable as the loop control variable of both an outer and an inner for loop in the same nest. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 35

An Example #include <stdio. h> main( ) { int I, j; for (i=1; i<=5

An Example #include <stdio. h> main( ) { int I, j; for (i=1; i<=5 ; i++){ for(j=1; j<=5; j++){ printf (“(%d, %d)”, I, j); } printf( “n”); } } 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 36

An Example (1, 1)(1, 2)(1, 3)(1, 4)(1, 5) (2, 1)(2, 2)(2, 3)(2, 4)(2, 5)

An Example (1, 1)(1, 2)(1, 3)(1, 4)(1, 5) (2, 1)(2, 2)(2, 3)(2, 4)(2, 5) (3, 1)(3, 2)(3, 3)(3, 4)(3, 5) (4, 1)(4, 2)(4, 3)(4, 4)(4, 5) (5, 1)(5, 2)(5, 3)(5, 4)(5, 5) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 37

5. 8 The do-while statement and flag-controlled loops v. The do-while (loop) statement do

5. 8 The do-while statement and flag-controlled loops v. The do-while (loop) statement do statement; while ( bool-expr ); do { stmts; }while ( bool-expr ); Yes statement Bool-expr ? No 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 38

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 39

中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 39

5. 8 (cont) Flag-Controlled Loops for Input Validation vflag ²A type int variable used

5. 8 (cont) Flag-Controlled Loops for Input Validation vflag ²A type int variable used to represent whether or not a certain event has occurred ²A flag has one of two values v 1 (true) (或 非 0值) v 0 (false) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 40

5. 8 (cont) Example 5. 10 (Figure 5. 14) v. Function get_int returns an

5. 8 (cont) Example 5. 10 (Figure 5. 14) v. Function get_int returns an integer value that is in the range specified by its two arguments. v. The outer do-while structure implements the stated purpose of the function. v. The type int variable error acts as a program flag. verror is initialized to 0 and is changed to 1 when an error is detected. 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 41

Figure 5. 14 Validating Input Using do-while Statement 中正大學通訊 程系 潘仁義老師 Advanced Network Technology

Figure 5. 14 Validating Input Using do-while Statement 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 42

5. 9 Problem Solving Illustrated Case Study: Collecting Area For Solar-Heated House v. Problem

5. 9 Problem Solving Illustrated Case Study: Collecting Area For Solar-Heated House v. Problem ²An architect needs a program that can estimate the appropriate size for the collecting area of a solar-heated house. ²Considerate factors v. Average number of heating degree days for the coldest month of a year v. The heating requirements per square foot of floor space v. Floor space v. Efficiency of the collection method 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 43

5. 9 (cont) Case Study: Collecting Area For Solar-Heated House v. Problem ²The program

5. 9 (cont) Case Study: Collecting Area For Solar-Heated House v. Problem ²The program will have to access two data files v. File hdd. txt ØContains numbers representing the average heating degree days in the construction location for each of 12 months v. File solar. txt ØContains the average solar insolation for each month 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 44

Solar-heated house Heating degree * days Solar insolation 日射能量 BTU / ft^2 / day

Solar-heated house Heating degree * days Solar insolation 日射能量 BTU / ft^2 / day Efficiency Area = heat loss / energy resource Floor space Heating requirement BTU / degree-day / ft^2 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 45

Problem solving illustrated BTU, 英制熱量單位 使 1磅(b)水升高華 氏 1度所需能量 日射能量 中正大學通訊 程系 潘仁義老師 Advanced

Problem solving illustrated BTU, 英制熱量單位 使 1磅(b)水升高華 氏 1度所需能量 日射能量 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 46

5. 9 (cont) Case Study: Collecting Area For Solar-Heated House v. Design ²Refinement v

5. 9 (cont) Case Study: Collecting Area For Solar-Heated House v. Design ²Refinement v 1. 1 Scan first value from heating degree days file into heat_deg_days, and initialize coldest_mon to 1. v 1. 2 Initialize ct to 2 v 1. 3 Scan a value from the file into next_hdd, saving status v 1. 4 as long as no faulty data/end of file, repeat Ø 1. 5 if next_hdd is greater than heat_deg_days » 1. 6 copy next_hdd into heat_deg_days » 1. 7 copy ct into coldest_days Ø 1. 8 Increment ct Ø 1. 9 Scan a value from the file into next_hdd, saving status 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 47

5. 9 (cont) Case Study: Collecting Area For Solar-Heated House v. Design ²Refinement v

5. 9 (cont) Case Study: Collecting Area For Solar-Heated House v. Design ²Refinement v 4. 1 Calculate heat_loss as the product of heating_req, floor_space, and heat_deg_days v 4. 2 Calculate energy_resrc as the product of efficiency, solar_insol, and the number of days in the coldest month v 4. 3 Calculate collect_area as heat_loss divided by energy_resrc. Round result to nearest whole square foot 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 48

5. 9 (cont) Case Study: Collecting Area For Solar-Heated House v. Design ²Functions vnth_item

5. 9 (cont) Case Study: Collecting Area For Solar-Heated House v. Design ²Functions vnth_item vdays_in_month ²Input file hdd. txt v 995 900 750 400 180 20 10 10 60 290 610 1051 ²Input file solar. txt v 500 750 1100 1490 1900 2100 2050 1550 1200 900 500 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 49

Figure 5. 15 Structure Chart for Computing Solar Collecting Area Size 中正大學通訊 程系 潘仁義老師

Figure 5. 15 Structure Chart for Computing Solar Collecting Area Size 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 50

Figure 5. 16 Program to Approximate Solar Collecting Area Size 好長哦… 直接看程式 中正大學通訊 程系

Figure 5. 16 Program to Approximate Solar Collecting Area Size 好長哦… 直接看程式 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 51

Figure 5. 16 Program to Approximate Solar Collecting Area Size (cont’d) 中正大學通訊 程系 潘仁義老師

Figure 5. 16 Program to Approximate Solar Collecting Area Size (cont’d) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 52

Figure 5. 16 Program to Approximate Solar Collecting Area Size (cont’d) 中正大學通訊 程系 潘仁義老師

Figure 5. 16 Program to Approximate Solar Collecting Area Size (cont’d) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 53

Figure 5. 16 Program to Approximate Solar Collecting Area Size (cont’d) 中正大學通訊 程系 潘仁義老師

Figure 5. 16 Program to Approximate Solar Collecting Area Size (cont’d) 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 54

5. 10 How to Debug and Test Programs v. Using debugger programs ²Execute programs

5. 10 How to Debug and Test Programs v. Using debugger programs ²Execute programs one statement at a time (single-step execution) ²Set breakpoints at selected statements when a program is very long v. Debugging without a debugger ²Insert extra diagnostic calls to printf that display intermediate results at critical points 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 55

How to debug and test programs v. Debugging without a debugger v. Off-by-one loop

How to debug and test programs v. Debugging without a debugger v. Off-by-one loop errors 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 56

5. 10 (cont) Off-by-One Loop Errors v. A common logic error ²A loop executes

5. 10 (cont) Off-by-One Loop Errors v. A common logic error ²A loop executes one more time or one less time v. Loop boundaries ²Initial and final values of the loop control variable 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 57

5. 11 Common Programming Errors v Do not confuse if and while statements ²if

5. 11 Common Programming Errors v Do not confuse if and while statements ²if statement implement a decision step ²while/for statement implement a loop v Remember to end the initialization expression and the loop repetition condition with semicolons. v Remember to use braces around a loop body consisting of multiple statements (compound statements) 不要括錯了 v Remember to provide a prompt for the users, when using a sentinel-controlled loop. v Make sure the sentinel value cannot be confused with a normal data item. v == and = 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 59

5. 11 (cont) Common Programming Errors v. Use do-while only when there is no

5. 11 (cont) Common Programming Errors v. Use do-while only when there is no possibility of zero loop iterations. v. Replace the segment with a while or for statement when adding an if statement. ²if (condition 1) do { … } while(condition 1); 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 60

5. 11 (cont) Common Programming Errors v. Do not use increment, decrement, or compound

5. 11 (cont) Common Programming Errors v. Do not use increment, decrement, or compound assignment operators as subexpressions in complex expressions. (difficult to read) v. Be sure that the operand of an increment or decrement operator is a variable. v. Do not use a variable twice in an expression in which it is incremented/decremented 中正大學通訊 程系 潘仁義老師 Advanced Network Technology Lab 61