Beruflich Dokumente
Kultur Dokumente
Loop: a control structure that repeats a group of steps in a program C loop control statements
while, for, and do-while
Loop Kinds
5-3
5-4
5-5
5-6
5-7
infinite loop
a loop that executes forever
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-8
5-9
5-10
5-11
5-12
5-13
5-15
5-16
postfix increment
++ comes immediately after the operand expressions value is the value of the variable before it is incremented
5-17
5-18
5-19
5-20
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.
5-22
5-23
5-24
5-25
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
5-28
5-29
} else {
fscanf(inp, "%c", &bad_char); printf("*** Error in input: %c ***\n", bad_char);
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.
5-31
Implementation
do {
printf("Enter a letter from A through E> "); scanf("%c", &letter_choice);
5-33
5-34
5-35
5-36
5-37
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
5-39
5-40
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;
5-41
The compiler will associate the first closing brace encountered with the innermost structure.
5-42
5-43
5-45