Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.

Similar presentations


Presentation on theme: "Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei."— Presentation transcript:

1 Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of Technology

2 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-2 Repetition in Programs Three types of program control structure: –sequence, selection, repetition Loop: a control structure that repeats a group of steps in a program C loop control statements –while, for, and do-while loop body: the statements that are repeated in the loop

3 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-3 Repetition in Programs (Cont’) After you solve the sample case, ask yourself some of the following questions to determine whether loops will be required in the general algorithm: –Were there any steps I repeated as I solved the problem? If so, which ones? –If the answer to question 1 is yes, did I know in advance how many times to repeat the steps? –If the answer to question 2 is no, how did I know how long to keep repeating the steps?

4 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-4 Figure 5.1 Flow Diagram of Loop Choice Process

5 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-5 Loop Kinds

6 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-6 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 Set loop control variable to an initial value of 0 while loop control variable < final value... Increase loop control variable by 1

7 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-7 The while Statement

8 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-8 The while Statement (Cont’) After executing the last step in the loop body, control returns to the line beginning with while and the condition is reevaluated. loop repetition condition –the condition that controls loop repetition

9 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-9 Figure 5.3 Flowchart for a while Loop

10 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-10 The while Statement (Cont’) The loop control variable count_emp must be (1) initialized, (2) tested, and (3) updated for the loop to execute properly. –Initialization. count_emp is set to an initial value of 0 (initialized to 0) before the while statement is reached. –Testing. count_emp is tested before the start of each loop repetition (called an iteration or a pass). –Updating. count_emp is updated (its value increased by 1) during each iteration. infinite loop –a loop that executes forever

11 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-11 The while Statement (Cont’)

12 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-12 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

13 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-13 Figure 5.4 Program to Compute Company Payroll

14 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-14 Multiplying a List of Numbers

15 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-15 Compound Assignment Operators variable = variable op (expression); variable op= expression;

16 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-16 The for Statement Review of the three loop control components –initialization of the loop control variable, –test of the loop repetition condition, and –change (update) of the loop control variable. /* Display nonnegative numbers < max */ for (i = 0; i < max; i += 1) printf("%d\n", i);

17 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-17 Figure 5.5 Using a for Statement in a Counting Loop

18 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-18

19 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-19 Increment and Decrement Operators The increment operator ++ takes a single variable as its operand. for (counter = 0; counter < limit; ++counter) prefix increment –++ is placed immediately in front of its operand –value of the expression is the variable’s value after incrementing postfix increment –++ comes immediately after the operand –expression’s value is the value of the variable before it is incremented

20 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-20 Figure 5.6 Comparison of Prefix and Postfix Increments

21 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-21 Increment and Decrement Operators (Cont’) avoid using the increment and decrement operators in complex expressions in which the variables to which they are applied appear more than once. Example: x = 5; i = 2; y = i * x + ++i; –Implementation dependent –13 (2 * 5 + 3) or (3 * 5 + 3)

22 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-22 Figure 5.7 Function to Compute Factorial

23 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-23 Figure 5.8 Displaying a Celsius-to- Fahrenheit Conversion Table

24 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-24 Conditional Loops 1.Print an initial prompting message. 2.Get the number of observed values. 3.while the number of values is negative 1)Print a warning and another prompting message. 2)Get the number of observed values.

25 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-25 Conditional Loops (Cont’) Example printf("Enter number of observed values> "); scanf("%d", &num_obs); /* initialization */ while (num_obs < 0) { printf("Negative number invalid; try again> "); scanf("%d", &num_obs); /* update */ }

26 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-26 Figure 5.9 Program to Monitor Gasoline Storage Tank

27 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-27 Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d)

28 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-28 Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d)

29 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-29 Sentinel-Controlled Loops One way to signal the program to stop reading and processing new data. sentinel value –an end marker that follows the last item in a list of data –The loop exits when the sentinel value is read. Structure –Get a line of data. –while the sentinel value has not been encountered Process the data line. Get another line of data.

30 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-30 Calculates the sum of scores Sentinel Loop –Initialize sum to zero. –Get first score. –while score is not the sentinel Add score to sum. Get next score. Incorrect Sentinel Loop –Initialize sum to zero. –while score is not the sentinel Get score Add score to sum

31 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-31 Figure 5.10 Sentinel-Controlled while Loop

32 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-32 Using a for Statement to Implement a Sentinel Loop /* 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); }

33 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-33 Endfile-Controlled Loops The return value of scanf is the number of data items it actually obtained. input_status = scanf("%d%d%lf", &part_id, &num_avail, &cost); –returns a result of 3 on success if scanf runs into difficulty with invalid or insufficient data, the function returns as its value the number of data items scanned before encountering the error or running out of data.

34 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-34 Endfile-Controlled Loops (Cont’) To detect the end-of-file condition, scanf returns as its result the value of the standard constant EOF 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

35 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-35 Figure 5.11 Batch Version of Sum of Exam Scores Program

36 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-36 Infinite Loops on Faulty Data assume the user responds to the prompt Enter next score (-99 to quit)> in Fig. 5.10 with the faulty data “7o” –Infinite loops!! Changing the loop repetition condition to –input_status == 1 To warn of bad input if (input_status == EOF) { printf("Sum of exam scores is %d\n", sum); } else { fscanf(inp, "%c", &bad_char); printf("*** Error in input: %c ***\n", bad_char); }

37 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-37 Nested Loops Do not use the same variable as the loop control variable of both an outer and an inner for loop in the same nest.

38 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-38 Figure 5.13 Nested Counting Loop Program

39 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-39 Figure 5.12 Program to Process Bald Eagle Sightings for a Year

40 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-40 The do-while Statement and Flag- Controlled Loops a loop must execute at least one time. Example –Get a data value. –If data value isn’t in the acceptable range, go back to step 1. Implementation do { printf("Enter a letter from A through E> "); scanf("%c", &letter_choice); } while (letter_choice 'E');

41 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-41

42 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-42 Flag-Controlled Loops for Input Validation flag –a type int variable used to represent whether or not a certain event has occurred

43 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-43 Figure 5.14 Validating Input Using do-while Statement

44 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-44 Flag-Controlled Loops for Input Validation (Cont’) Execution results Enter an integer in the range from 10 to 20 inclusive> @20 Invalid character >>@>>. Skipping rest of line. Enter an integer in the range from 10 to 20 inclusive> 2o Number 2 is not in range. Enter an integer in the range from 10 to 20 inclusive> 20

45 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-45 Figure 5.15 Structure Chart for Computing Solar Collecting Area Size

46 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-46 Figure 5.16 Program to Approximate Solar Collecting Area Size

47 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-47 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

48 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-48 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

49 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-49 Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d)

50 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-50 How to Debug and Test Programs The first step in locating a hidden error is to examine the program output to determine which part of the program is generating incorrect results.

51 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-51 Using Debugger Programs single-step execution –execute your program one statement at a time Trace your program’s execution and observe the effect of each C statement on variables you select A breakpoint is like a fence between two segments of a program. When the program stops at a breakpoint, you can examine the values of selected variables to determine whether the program segment has executed correctly.

52 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-52 Debugging without a Debugger Insert extra diagnostic calls to printf that display intermediate results at critical points in your program. By comparing these results at the end of a run, you may be able to determine which segment of your program contains bugs.

53 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-53 Debugging without a Debugger (Cont’) Example while (score != SENTINEL) { sum += score; if (DEBUG) printf("***** score is %d, sum is %d\n", score, sum); printf("Enter next score (%d to quit)> ", SENTINEL); scanf("%d", &score); /* Get next score. */ } turn your diagnostics on by inserting –#define DEBUG 1

54 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-54 Off-by-One Loop Errors loop boundaries –initial and final values of the loop control variable Make sure that the initial and final values of the loop control variable are correct and that the loop repetition condition is right. Example for (count = 0; count <= n; ++count) sum += count;

55 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-55 Common Programming Errors 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. while (x > xbig) x -= 2; ++xbig; –The compiler will associate the first closing brace encountered with the innermost structure.

56 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-56 Common Programming Errors (Cont’)

57 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-57 Common Programming Errors (Cont’) Be sure to verify that a loop’s repetition condition will eventually become false (0); otherwise, an infinite loop may result. An equality test mistyped as an assignment operation do {... printf("One more time? (1 to continue/0 to quit)> "); scanf("%d", &again); } while (again = 1); /* should be: again == 1 */

58 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.5-58 Common Programming Errors (Cont’) Use a do-while only when there is no possibility of zero loop iterations. a *= b + c; is equivalent to a = a * (b + c);


Download ppt "Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei."

Similar presentations


Ads by Google