Sie sind auf Seite 1von 45

Repetition in Programs Loops

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


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

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

Loop Kinds

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-3

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-4

The while Statement

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-5

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-6

Figure 5.3 Flowchart for a while Loop

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-7

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

The while Statement (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-9

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-10

Figure 5.4 Program to Compute Company Payroll

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-11

Multiplying a List of Numbers

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-12

Compound Assignment Operators


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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-13

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);
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-14

Figure 5.5 Using a for Statement in a Counting Loop

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-15

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-16

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 variables value after incrementing

postfix increment
++ comes immediately after the operand expressions value is the value of the variable before it is incremented

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-17

Figure 5.6 Comparison of Prefix and Postfix Increments

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-18

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)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-19

Figure 5.7 Function to Compute Factorial

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-20

Figure 5.8 Displaying a Celsius-toFahrenheit Conversion Table

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-21

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.

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-22

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 */

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-23

Figure 5.9 Program to Monitor Gasoline Storage Tank

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-24

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-25

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-26

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

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-28

Figure 5.11 Batch Version of Sum of Exam Scores Program

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-29

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-30

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.

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-31

The do-while Statement and FlagControlled Loops


a loop must execute at least one time. Example
Get a data value. If data value isnt 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 < 'A' || letter_choice > 'E');


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

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-33

Figure 5.16 Program to Approximate Solar Collecting Area Size (contd)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-34

Figure 5.16 Program to Approximate Solar Collecting Area Size


(contd)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-35

Figure 5.16 Program to Approximate Solar Collecting Area Size (contd)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-36

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.

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-37

Using Debugger Programs


single-step execution
execute your program one statement at a time

Trace your programs 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.
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-38

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.

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-39

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-40

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;

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-41

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.

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-42

Common Programming Errors (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-43

Common Programming Errors (Cont)


Be sure to verify that a loops 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 */


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

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

5-45

Das könnte Ihnen auch gefallen