Chapter 5 Repetition and Loop Statements Dr. J.-Y. Pan Dept. Comm. Eng. Nat. Chung Cheng Univ.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab Repetition in programs Loop A control structure that repeats a group of steps in a program Loop body The statements that are repeated in the loop Three questions to determine whether loops will be required in the general algorithm: (Figure5.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 3-3 Figure 5.1 Flow Diagram of Loop Choice Process
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-4
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-5 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 Counting Loops and the while Statement Counter-controlled loop (counting loop) A loop whose required number of iterations can be determined before loop execution begins Figure 5.2 shows a program fragment that computes and displays the gross pay for seven employees.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-7 Figure 5.2 Program Fragment with a Loop
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-8 Figure 5.3 Flowchart for a while Loop
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Counting Loops and the while Statement Loop repetition condition The condition that controls loop repetition Loop control variable The variable whose value controls loop repetition The loop control variable must be Initialization Testing Updating
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab Computing a Sum or a Product in a Loop accumulator a variable used to store a value being computed in increments during the execution of a loop Fig.5.4 Program to Compute Company Payroll
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-11 Figure 5.4 Program to Compute Company Payroll
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-12 Figure 5.4 Program to Compute Company Payroll (cont’d) 跑個 GDB?
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-13
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Compound Assignment Operators Assignment statements of the form variable = variable op expression variable op = expression 如 += -= /= %= /=
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab The for Statement Three loop control components Initialization of the loop variable Test of the loop repetition condition Change (update) of the loop control variable Using a for statement in a counting loop. (Figure 5.5)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-16 Figure 5.5 Using a for Statement in a Counting Loop
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-17 The for statement The for (loop) statement for (init expr; loop condition; step expr) { stmts; } Initial expression Loop condition Step expression statements Yes No
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-18 An Example #include 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 3-19 Increment and decrement operators 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 3-20 Figure 5.6 Comparison of Prefix and Postfix Increments
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-21 Conditional loops 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 (cont) Example 5.5 (Figure 5.9) The program is designed to assist in monitoring the gasoline supply in a storage tank at the Super Oil Company refinery. 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. The barrel used in the petroleum industry equals 42 U.S. gallons
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-23 Figure 5.9 Program to Monitor Gasoline Storage Tank
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-24 Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-25 Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Example 5.5 (Figure 5.9) 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 3-27 Loop design… An example on Ex 5.5 (Fig 5.9) Fig 5.1
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-28 Loop design Sentinel-Controlled Loops 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 (cont) Example 5.6 (Figure 5.10) A program that calculates the sum of a collection of exam scores is a candidate for using a sentinel value. 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 3-30 Figure 5.10 Sentinel-Controlled while Loop
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Using a for Statement to Implement a Sentinel Loop 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 3-32 Endfile-controlled loops Here is the pseudo code for an endfile- controlled loop: get the first data value and save input status while input status does not indicate that end of file has been reached process data value get next data value and save input status
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-33 Result value of scanf and fscanf input_status = scanf(“%d%d%lf”,&a, &b, &c); number of data items it actually obtained number of data before encountering error EOF: when detecting the endfile before get (End of File)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-34 Figure 5.11 Batch Version of Sum of Exam Scores Program
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-35 Nested loop 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 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 3-36 An Example #include 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 3-37 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 The do-while statement and flag-controlled loops The do-while (loop) statement do statement; while ( bool-expr ); do { stmts; }while ( bool-expr ); statement Bool-expr ? No Yes
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-39
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Flag-Controlled Loops for Input Validation flag A type int variable used to represent whether or not a certain event has occurred A flag has one of two values 1 (true) ( 或 非 0 值 ) 0 (false)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Example 5.10 (Figure 5.14) Function get_int returns an integer value that is in the range specified by its two arguments. The outer do-while structure implements the stated purpose of the function. The type int variable error acts as a program flag. error is initialized to 0 and is changed to 1 when an error is detected.
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-42 Figure 5.14 Validating Input Using do-while Statement
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab Problem Solving Illustrated Case Study : Collecting Area For Solar-Heated House Problem An architect needs a program that can estimate the appropriate size for the collecting area of a solar-heated house. Considerate factors Average number of heating degree days for the coldest month of a year The heating requirements per square foot of floor space Floor space Efficiency of the collection method
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Case Study : Collecting Area For Solar-Heated House Problem The program will have to access two data files File hdd.txt Contains numbers representing the average heating degree days in the construction location for each of 12 months File solar.txt Contains the average solar insolation for each month
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-45 Solar-heated house Heating degree * days Heating requirement BTU / degree-day / ft^2 Floor space Solar insolation 日射能量 BTU / ft^2 / day Efficiency Area = heat loss / energy resource
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-46 Problem solving illustrated BTU, 英制熱量單位 使 1 磅 (b) 水升高華 氏 1 度所需能量 日射能量
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Case Study : Collecting Area For Solar-Heated House Design Refinement 1.1 Scan first value from heating degree days file into heat_deg_days, and initialize coldest_mon to 1. 1.2 Initialize ct to 2 1.3 Scan a value from the file into next_hdd, saving status 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 (cont) Case Study : Collecting Area For Solar-Heated House Design Refinement 4.1 Calculate heat_loss as the product of heating_req, floor_space, and heat_deg_days 4.2 Calculate energy_resrc as the product of efficiency, solar_insol, and the number of days in the coldest month 4.3 Calculate collect_area as heat_loss divided by energy_resrc. Round result to nearest whole square foot
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Case Study : Collecting Area For Solar-Heated House Design Functions nth_item days_in_month Input file hdd.txt Input file solar.txt
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-50 Figure 5.15 Structure Chart for Computing Solar Collecting Area Size
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-51 Figure 5.16 Program to Approximate Solar Collecting Area Size 好長哦 … 直接看程式
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-52 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-53 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-54 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab How to Debug and Test Programs Using debugger programs Execute programs one statement at a time (single-step execution) Set breakpoints at selected statements when a program is very long Debugging without a debugger Insert extra diagnostic calls to printf that display intermediate results at critical points
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-56 How to debug and test programs Debugging without a debugger Off-by-one loop errors
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Off-by-One Loop Errors A common logic error A loop executes one more time or one less time Loop boundaries Initial and final values of the loop control variable
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab 3-58 補充資料 break 強制離開這層迴圈 continue 強制進行下次迴圈
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab Common Programming Errors Do not confuse if and while statements if statement implement a decision step while/for statement implement a loop Remember to end the initialization expression and the loop repetition condition with semicolons. Remember to use braces around a loop body consisting of multiple statements (compound statements) 不要括錯了 Remember to provide a prompt for the users, when using a sentinel-controlled loop. Make sure the sentinel value cannot be confused with a normal data item. == and =
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Common Programming Errors Use do-while only when there is no possibility of zero loop iterations. Replace the segment with a while or for statement when adding an if statement. if (condition 1 ) do { … } while(condition1);
中正大學通訊工程系 潘仁義老師 Advanced Network Technology Lab (cont) Common Programming Errors Do not use increment, decrement, or compound assignment operators as subexpressions in complex expressions. (difficult to read) Be sure that the operand of an increment or decrement operator is a variable. Do not use a variable twice in an expression in which it is incremented/decremented