control struc
TRANSCRIPT
-
7/30/2019 Control Struc
1/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-1
Repetition in Programs Loops
Three types of program control structure:
sequence, selection, repetition
Loop: a control structure that repeats agroup of steps in a program
C loop control statements
while, for, and do-while
loop body: the statements that are
repeated in the loop
-
7/30/2019 Control Struc
2/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-2
Repetition in Programs (Cont)
After you solve the sample case, askyourself some of the following questions todetermine 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 knowhow long to keep repeating the steps?
-
7/30/2019 Control Struc
3/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-3
Loop Kinds
-
7/30/2019 Control Struc
4/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-4
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/30/2019 Control Struc
5/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-5
The while Statement
-
7/30/2019 Control Struc
6/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-6
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
-
7/30/2019 Control Struc
7/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-7
Figure 5.3 Flowchart for a while Loop
-
7/30/2019 Control Struc
8/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-8
The while Statement (Cont)
The loop control variable count_emp must be (1)initialized, (2) tested, and (3) updated for the loopto 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 eachloop repetition (called an iteration or apass).
Updating. count_emp is updated (its value increased
by 1) during each iteration. infinite loop
a loop that executes forever
-
7/30/2019 Control Struc
9/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-9
The while Statement (Cont)
-
7/30/2019 Control Struc
10/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-10
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
-
7/30/2019 Control Struc
11/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-11
Figure 5.4 Program to Compute Company
Payroll
-
7/30/2019 Control Struc
12/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-12
Multiplying a List of Numbers
-
7/30/2019 Control Struc
13/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-13
Compound Assignment Operators
variable =variable op(expression);
variable op=expression;
-
7/30/2019 Control Struc
14/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-14
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);
-
7/30/2019 Control Struc
15/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-15
Figure 5.5 Using a for Statement in a
Counting Loop
-
7/30/2019 Control Struc
16/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-16
-
7/30/2019 Control Struc
17/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-17
Increment and Decrement Operators
The increment operator++ takes a single variableas 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 afterincrementing
postfix increment
++ comes immediately after the operand expressions value is the value of the variable before it
is incremented
-
7/30/2019 Control Struc
18/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-18
Figure 5.6 Comparison of Prefix and Postfix
Increments
-
7/30/2019 Control Struc
19/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-19
Increment and Decrement Operators (Cont)
avoid using the increment and decrementoperators in complex expressions in which thevariables to which they are applied appear morethan once.
Example:x = 5;
i = 2;
y = i * x + ++i; Implementation dependent
13 (2 * 5 + 3) or (3 * 5 + 3)
-
7/30/2019 Control Struc
20/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-20
Figure 5.7 Function to Compute Factorial
-
7/30/2019 Control Struc
21/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-21
Figure 5.8
Displaying
a Celsius-to-Fahrenheit
Conversion
Table
-
7/30/2019 Control Struc
22/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-22
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.
-
7/30/2019 Control Struc
23/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-23
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 */
}
-
7/30/2019 Control Struc
24/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-24
Figure 5.9
Program to
MonitorGasoline
Storage Tank
-
7/30/2019 Control Struc
25/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-25
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
-
7/30/2019 Control Struc
26/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-26
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);
}
-
7/30/2019 Control Struc
27/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-27
Endfile-Controlled Loops
The return value ofscanfis 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.
-
7/30/2019 Control Struc
28/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-28
Endfile-Controlled Loops (Cont)
To detect the end-of-file condition, scanfreturns as its result the value of the standardconstant EOF
Endfile-controlled loop: Get the first data value and save input status
While input status does not indicate that end offile has been reached Process data value
Get next data value and save input status
-
7/30/2019 Control Struc
29/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-29
Figure 5.11
Batch
Version ofSum of
Exam
ScoresProgram
-
7/30/2019 Control Struc
30/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-30
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 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);
}
-
7/30/2019 Control Struc
31/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-31
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.
-
7/30/2019 Control Struc
32/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-32
The do-while Statement and Flag-
Controlled Loops
a loop must execute at least one time.
Example
Get a data value.
Ifdata value isnt in the acceptable range, go back tostep 1.
Implementation
do {
printf("Enter a letter from A through E> ");
scanf("%c", &letter_choice);
} while (letter_choice < 'A' || letter_choice > 'E');
-
7/30/2019 Control Struc
33/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-33
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
-
7/30/2019 Control Struc
34/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-34
Figure 5.16
Program to
ApproximateSolar Collecting
Area Size (contd)
-
7/30/2019 Control Struc
35/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-35
Figure 5.16
Program to
ApproximateSolar Collecting
Area Size(contd)
-
7/30/2019 Control Struc
36/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-36
Figure 5.16
Program to
ApproximateSolar Collecting
Area Size (contd)
-
7/30/2019 Control Struc
37/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-37
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.
-
7/30/2019 Control Struc
38/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-38
Using Debugger Programs
single-step execution execute your program one statement at a time
Trace your programs execution and observe theeffect of each C statement on variables you select
A breakpoint is like a fence between twosegments of a program.
When the program stops at a breakpoint, you can
examine the values of selected variables todetermine whether the program segment hasexecuted correctly.
-
7/30/2019 Control Struc
39/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-39
Debugging without a Debugger
Insert extra diagnostic calls toprintfthat
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.
-
7/30/2019 Control Struc
40/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-40
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
-
7/30/2019 Control Struc
41/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-41
Off-by-One Loop Errors
loop boundaries
initial and final values of the loop controlvariable
Make sure that the initial and final values ofthe loop control variable are correct and thatthe loop repetition condition is right.
Example
for (count = 0; count
-
7/30/2019 Control Struc
42/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-42
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 braceencountered with the innermost structure.
-
7/30/2019 Control Struc
43/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-43
Common Programming Errors (Cont)
-
7/30/2019 Control Struc
44/45
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 5-44
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 assignmentoperation
do {
. . .
printf("One more time? (1 to continue/0 to quit)> ");scanf("%d", &again);
} while (again = 1); /* should be: again == 1 */
-
7/30/2019 Control Struc
45/45
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);