Presentation is loading. Please wait.

Presentation is loading. Please wait.

Repetition and Loop Statements

Similar presentations


Presentation on theme: "Repetition and Loop Statements"— Presentation transcript:

1 Repetition and Loop Statements
Chapter 5 Repetition and Loop Statements Dr. J.-Y. Pan Dept. Comm. Eng. Nat. Chung Cheng Univ.

2 5.1 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?

3 Figure 5.1 Flow Diagram of Loop Choice Process

4

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.

6 5.2 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.

7 Figure 5.2 Program Fragment with a Loop

8 Figure 5.3 Flowchart for a while Loop

9 5.2 (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

10 5.3 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

11 Figure 5.4 Program to Compute Company Payroll

12 Figure 5.4 Program to Compute Company Payroll (cont’d)
跑個GDB?

13

14 5.3 (cont) Compound Assignment Operators
Assignment statements of the form variable = variable op expression variable op = expression 如 += -= /= %= /=

15 Three loop control components
5.4 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)

16 Figure 5.5 Using a for Statement in a Counting Loop

17 The for statement The for (loop) statement
for (init expr; loop condition; step expr) { stmts; } Initial expression Loop condition No Step expression Yes statements

18 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吧…

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

20 Figure 5.6 Comparison of Prefix and Postfix Increments

21 Conditional loops In many programming situations, you will not be able to determine the exact number of loop repetitions before loop execution begins.

22 5.5 (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

23 Figure 5.9 Program to Monitor Gasoline Storage Tank

24 Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d)

25 Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d)

26 5.5 (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

27 Loop design… An example on Ex 5.5 (Fig 5.9)
5.1

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

29 5.6 (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 會很怪嗎?

30 Figure 5.10 Sentinel-Controlled while Loop

31 5.6 (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); }

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

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)

34 Figure 5.11 Batch Version of Sum of Exam Scores Program

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.

36 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”);

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)

38 5.8 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 ? Yes No

39

40 5.8 (cont) Flag-Controlled Loops for Input Validation
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)

41 5.8 (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.

42 Figure 5.14 Validating Input Using do-while Statement

43 5.9 Problem Solving Illustrated Case Study: Collecting Area For Solar-Heated House
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

44 5.9 (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

45 Solar-heated house Heating degree * days Solar insolation 日射能量
BTU / ft^2 / day Floor space Efficiency Area = heat loss / energy resource Heating requirement BTU / degree-day / ft^2

46 Problem solving illustrated
BTU, 英制熱量單位 使1磅(b)水升高華氏1度所需能量 Problem solving illustrated 日射能量

47 5.9 (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

48 5.9 (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

49 5.9 (cont) Case Study: Collecting Area For Solar-Heated House
Design Functions nth_item days_in_month Input file hdd.txt Input file solar.txt

50 Figure 5.15 Structure Chart for Computing Solar Collecting Area Size

51 Figure 5.16 Program to Approximate Solar Collecting Area Size
好長哦… 直接看程式

52 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

53 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

54 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

55 5.10 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

56 How to debug and test programs
Debugging without a debugger Off-by-one loop errors

57 5.10 (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

58 補充資料 break 強制離開這層迴圈 continue 強制進行下次迴圈

59 5.11 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 =

60 5.11 (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 (condition1) do { } while(condition1);

61 5.11 (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


Download ppt "Repetition and Loop Statements"

Similar presentations


Ads by Google