chapter 5 repetition and loop statements j. h. wang ( 王正豪 ), ph. d. assistant professor dept....

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

Upload: kristin-dalton

Post on 13-Jan-2016

229 views

Category:

Documents


2 download

TRANSCRIPT

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

Chapter 5Repetition and Loop Statements

J. H. Wang (王正豪 ), Ph. D.

Assistant Professor

Dept. Computer Science and Information Engineering

National Taipei University of Technology

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

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

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

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?

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

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

Figure 5.1 Flow Diagram of Loop Choice Process

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

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

Loop Kinds

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

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

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

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

The while Statement

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

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

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

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

Figure 5.3 Flowchart for a while Loop

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

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

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

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

The while Statement (Cont’)

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

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

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

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

Figure 5.4 Program to Compute Company Payroll

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

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

Multiplying a List of Numbers

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

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

Compound Assignment Operators

• variable = variable op (expression);• variable op= expression;

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

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

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

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

Figure 5.5 Using a for Statement in a Counting Loop

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

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

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

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

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

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

Figure 5.6 Comparison of Prefix and Postfix Increments

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

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)

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

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

Figure 5.7 Function to Compute Factorial

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

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

Figure 5.8 Displaying a Celsius-to-Fahrenheit Conversion Table

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

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 negative1) Print a warning and another prompting

message.

2) Get the number of observed values.

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

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

Conditional Loops (Cont’)

• Exampleprintf("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 */

}

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

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

Figure 5.9 Program to Monitor Gasoline Storage Tank

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

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

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

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

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

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

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

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.

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

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

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

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

Figure 5.10 Sentinel-Controlled while Loop

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

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

}

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

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.

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

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

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

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

Figure 5.11 Batch Version of Sum of Exam Scores Program

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

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

Infinite Loops on Faulty Data

• assume the user responds to the promptEnter 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 inputif (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);

}

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

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.

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

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

Figure 5.13 Nested Counting Loop Program

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

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

Figure 5.12 Program to Process Bald Eagle Sightings for a Year

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

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.

• Implementationdo {

printf("Enter a letter from A through E> ");

scanf("%c", &letter_choice);

} while (letter_choice < 'A' || letter_choice > 'E');

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

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

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

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

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

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

Figure 5.14 Validating Input Using do-while Statement

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

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

Flag-Controlled Loops for Input Validation (Cont’)

• Execution resultsEnter 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

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

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

Figure 5.15 Structure Chart for Computing Solar Collecting Area Size

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

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

Figure 5.16 Program to Approximate Solar Collecting Area Size

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

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

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

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

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

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

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

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

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

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

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.

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

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.

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

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.

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

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

Debugging without a Debugger (Cont’)

• Examplewhile (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

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

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.

• Examplefor (count = 0; count <= n; ++count)

sum += count;

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

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.

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

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

Common Programming Errors (Cont’)

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

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 operationdo {

. . .

printf("One more time? (1 to continue/0 to quit)> ");

scanf("%d", &again);

} while (again = 1); /* should be: again == 1 */

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

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