Chapter 5
Repetition
and Loop
Statements
Outline
5.1 REPETITION IN PROGRAMS
5.2 COUNTING LOOPS AND THE WHILE STATEMENT
5.3 COMPUTING A SUM OR A PRODUCT IN A LOOP
5.4 THE FOR STATEMENT
5.5 CONDITIONAL LOOPS
5.6 LOOP DESIGN
5.7 NESTED LOOPS
5.8 THE DO-WHILE STATEMENT AND FLAG-CONTROLLED
LOOPS
5.9 PROBLEM SOLVING ILLUSTRATED
CASE STUDY: COMPUTING RADIATION LEVELS
5.10 HOW TO DEBUG AND TEST PROGRAMS
5.11 COMMON PROGRAMMING ERRORS
52
Three types of program structure
sequence
selection
repetition This chapter
The repetition of steps in a program is called
loop
This chapter discuss three C loop control
statement
while
for
do-while
53
5.1 Repetition in programs
Loop
Loop body
A control structure that repeats a group of steps in a
program
The statements that are repeated in the loop
Three questions to determine whether loops will be
required in the general algorithm: (Figure5.1)
1. Were there any steps I repeated as I solved the problem? If
so, which ones?
2. If the answer to question 1 is yes, did I know in advance
how many times to repeat the steps?
3. If the answer to question 2 is no, how did I know how long
to keep repeating the steps?
54
Figure 5.1 Flow Diagram of Loop Choice Process
55
Table 5.1 Comparison of Loop Kinds (Page 211)
Kind
When Used C Implementation
Structure
Section
Containing an
Example
while
for
while, for
5.2
5.4
Endfilecontroller loop
while, for
5.6
Input validation
loop
do-while
5.8
General
conditional loop
while, for
5.5, 5.9
Counting loop
Sentinelcontrolled loop
5.6
56
5.2 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
Figure 5.2 shows a program fragment that
computes and displays the gross pay for seven
employees.
57
Figure 5.2 Program Fragment with a Loop
58
Flowchart for a while Loop
Looprepetitioncondition
statement
59
The while Statement
Loop repetition condition
The condition that controls loop repetition
Loop control variable
The variable whose value controls loop repetition
The loop control variable must be
Initialization
Testing
Updating
510
Syntax of the while Statement
Syntax while (loop repetition condition)
statement
Example /* Display N asterisks. */
count_star = 0
while (count_star < N) {
printf(*)
count_star = count_star + 1
}
511
5.3 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
Fig.5.4 Program to Compute Company Payroll
512
Figure 5.4 Program to Compute Company Payroll
513
Figure 5.4 Program to Compute Company Payroll
(contd)
514
Compound Assignment Operators
Assignment statements of the form
variable = variable op expression
Where op is a C arithmetic operator
variable op = expression
Table 5.3
Ex. time = time 1; time -= 1;
515
Compound Assignment Operators
Simple Assignment
Operators
count_emp = count_emp
+ 1;
Compound Assignment
Operators
count_emp += 1;
time = time -1;
product = product *
item;
time -= 1;
product *= item;
total = total /
number;
total /= number;
n = n % (x+1);
n %= x+1;
516
5.4 The for Statement
Three loop control components
Initialization of the loop variable
Test of the loop repetition condition
Change (update) of the loop control variable
Using a for statement in a counting loop.
(Figure 5.5)
517
Figure 5.5
Using a for Statement in a Counting Loop
518
Syntax of for Statement
Syntax: for (initialization expression;
loop repetition condition;
update expression)
statement
Example: /* Display N asterisks */
for (count_star = 0; count_star <N; count_star += 1)
printf(*);
519
Increment and Decrement Operators
Side effect
a change in the value of a variable as a result of
carrying out an operation
520
Figure 5.6
Comparison of Prefix and Postfix Increments
521
Example 5.3
Function factorial computes the factorial of an
integer represented by the formal parameter n.
The loop body executes for decreasing values
of i from n through 2, and each value of i is
incorporated in the accumulating product. Loop
exit occurs when i is 1. (Figure 5.7)
522
Figure 5.7 Function to Compute Factorial
523
Increments and Decrements Other Than 1
Example 5.4
Use a loop that counts down by five to display a
Celsius-to-Fahrenheit conversion table. (Figure
5.8)
524
Figure 5.8 Displaying a Celsius-to-Fahrenheit Conversion
525
5.5 Conditional Loops
Not be able to determine the exact number of
loop repetitions before loop execution begins
Ex.
Print an initial prompting message
Get the number of observed values
While the number of values is negative
Print a warning and another prompting message
Get the number of observed values
526
Example 5.5
(Figure 5.9)
The program is designed to assist in monitoring
the gasoline supply in a storage tank at the
Super Oil Company refinery.
The program is to alert the supervisor when the
supply of gasoline in the tank falls below 10% of
the tanks 80,000 barrel storage capacity.
The barrel used in the petroleum industry
equals 42 U.S. gallons
527
Figure 5.9 Program to Monitor Gasoline Storage Tank 528
Loop
repetition
Figure 5.9 Program to Monitor Gasoline Storage Tank (contd)
529
Figure 5.9 Program to Monitor Gasoline Storage
Tank (contd)
Warningmessageafter
runningoutoftheloop
inmonitor_gas
530
Example 5.5
(Figure 5.9)
There are three critical steps in Fig.5.9 that
involve the loop control variable current:
current is initialized to the starting supply in the for
statement initialization expression
current is tested before each execution of the loop
body
current is updated (by subtraction of the amount
removed) during each iteration
531
5.6 Loop Design
Sentinel value
An end marker that follows the last item in a list of
data
A loop that processes data until the sentinel
value is entered has the form
1. Get a line of data
2. while the sentinel value has not been encountered
3. Process the data line
4. Get another line of data
For program readability, we usually name the sentinel
by defining a constant macro.
532
Problem-Solving Questions for Loop
Design (pp. 239)
Question
Answer
Implications for
the Algorithm
What are the inputs?
Initial supply
Amounts removed
start_supply
remov_gals
What are the outputs?
amount removed
current supply
remov_gals
current
Is there any repetition?
yes
Do I know in advance how many
times steps will be repeated?
no
How do I know how long to
keep repeating the steps?
As long as the
current supply is
not below the
minimum
subprogram
monitor_gas
condition:
current >=min_supply
533
Example 5.6
(Figure 5.10)
A program that calculates the sum of a
collection of exam scores is a candidate for
using a sentinel value.
Sentinel loop
Beforethewhileloop
1. Initialize sum to zero
2. Get first score
3. while score is not the sentinel
4. Add score to sum
5. Get next score
534
Example 5.6 (cont)
(Figure 5.10)
Incorrect sentinel loop
1. Initialize sum to zero
2. while score is not the sentinel
3. Get score
4. Add score to sum
Two problems
No initializing input statement
Sentinel value will be added to sum before exit
535
Figure 5.10 Sentinel-Controlled while Loop
536
Sentinel-Controlled Structure
One input to get the loop going (initialization)
Second to keep it going (updating)
537
Using a for Statement to Implement a
Sentinel Loop
The for statement form of the while loop in Fig.5.10
/* 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);
}
538
Endfile-Controlled Loops
Pseudocode for an endfile-controlled loop
1. Get the first data values and save input status
2. While input status does not indicate that end of file
has been reached
3. Process data value
4. Get next data value and save input status
539
Figure 5.11 Batch Version of Sum of Exam Scores Program
540
5.7 Nested Loops
Nested loops consist of an outer loop with one
or more inner loops.
Example 5.7 (Figure 5.12)
The program contains a sentinel loop nested within
a counting loop.
541
Innerloop
Figure 5.12 Program to Process Bald Eagle Sightings for a Year
542
Figure 5.12 Program to Process Bald Eagle
Sightings for a Year (contd)
543
Example 5.8
(Figure 5.13)
A sample run of a program with two nested
counting loops.
Not be able to use the same variable as the
loop control variable of both an outer and an
inner for loop in the same nest.
544
Figure 5.13
Nested
Counting
Loop
Program
545
5.8 The do-while Statement and FlagControlled Loops
do-while statement execute at least one time.
Pseudocode
1. Get data value
2. If data value isnt in the acceptable range, go back
to step 1.
546
Syntax of do-while Statement
Syntax
do
statement
while (loop repetition condition);
Example
/* Find first even number input */
do
status = scanf(%d, &num)
while (status>0 && (num%2) != 0)
547
Flag-Controlled Loops for Input
Validation
flag
A type int variable used to represent whether or not
a certain event has occurred
A flag has one of two values
1 (true)
0 (false)
548
Example 5.10
(Figure 5.14)
Function get_int returns an integer value that is
in the range specified by its two arguments.
The outer do-while structure implements the
stated purpose of the function.
The type int variable error acts as a program
flag.
error is initialized to 0 and is changed to 1 when
an error is detected.
549
Figure 5.14 Validating Input Using do-while Statement
550
5.9 Problem Solving Illustrated
Case Study
Collecting Area For Solar-Heated House
Problem
An architect needs a program that can estimate the
appropriate size for the collecting area of a solarheated house.
Considerate factors
Average number of heating degree days for the coldest
month of a year
The heating requirements per square foot of floor space
Floor space
Efficiency of the collection method
551
Case Study
Collecting Area For Solar-Heated House (cont)
Problem
The program will have to access two data files
File hdd.txt
Contains numbers representing the average heating degree days
in the construction location for each of 12 months
Heating degree days
= average temperature difference between insides and outside
* number of days in the month
File solar.txt
Contains the average solar insolation for each month
(rate at which solar radiation falls on one square foot of a given location)
552
Case Study
Collecting Area For Solar-Heated House (cont)
Analysis
Problem Inputs
File: average heating degree days, average solar insolation
heat_deg_days, coldest_mon
solar_insol, heating_req
efficiency, floor_space
desired collecting area A
heat loss
energy resource
heat loss = heating_req * floor_space * heat_deg_days
energy resource = efficiency * 0.01 * solar_insol * days
553
Case Study
Collecting Area For Solar-Heated House (cont)
Analysis
Problem Variables
energy_resrc
Problem Output
heat_loss
collect_area
554
Case Study
Collecting Area For Solar-Heated House (cont)
Design
Initial Algorithm
1. Determine the coldest month and the average heating
degree days for this month.
2. Find the average daily solar insolation per ft 2 for the
coldest month.
3. Get from the user the other problem inputs: heating_req,
efficiency, and floor_space.
4. Estimate the collection area needed.
5. Display results.
555
Case Study
Collecting Area For Solar-Heated House (cont)
Design
Refinement
1.1 Scan first value from heating degree days file into
heat_deg_days, and initialize coldest_mon to 1.
1.2 Initialize ct to 2
1.3 Scan a value from the file into next_hdd, saving status
1.4 as long as no faulty data/end of file, repeat
1.5 if next_hdd is greater than heat_deg_days
1.6 copy next_hdd into heat_deg_days
1.7 copy ct into coldest_days
1.8 Increment ct
1.9 Scan a value from the file into next_hdd, saving status
556
Case Study
Collecting Area For Solar-Heated House (cont)
Design
Refinement
4.1 Calculate heat_loss as the product of heating_req,
floor_space, and heat_deg_days
4.2 Calculate energy_resrc as the product of efficiency,
solar_insol, and the number of days in the coldest
month
4.3 Calculate collect_area as heat_loss divided by
energy_resrc. Round result to nearest whole square foot
557
Case Study
Collecting Area For Solar-Heated House (cont)
Design
Functions
nth_item
days_in_item
Input file hdd.txt
995 900 750 400 180 20 10 10 60 290 610 1051
Input file solar.txt
500 750 1100 1490 1900 2100 2050 1550 1200 900 500
500
558
Figure 5.15 Structure Chart for Computing Solar
Collecting Area Size
559
Figure 5.16 Program to Approximate Solar
Collecting Area Size
560
Figure 5.16 Program to Approximate Solar Collecting Area Size
(contd)
561
Figure 5.16 Program to Approximate Solar Collecting Area Size
(contd)
562
Figure 5.16 Program to Approximate Solar Collecting Area Size
(contd)
563
5.10 How to Debug and Test Programs
Using debugger programs
Execute programs one statement at a time (singlestep execution)
Set breakpoints at selected statements when a
program is very long
Debugging without a debugger
Insert extra diagnostic calls to printf that display
intermediate results at critical points
#define DEBUG 1
#define DEBUG 0
564
Example: debug using printf
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);
}
#defineDEBUG1turnondiagnostics
#defineDEBUG0turnoff
565
Off-by-One Loop Errors
A common logic error
A loop executes one more time or one less time
executen+1time
for (count = 0; count <= n; ++count)
sum += count;
Loop boundaries
Initial and final values of the loop control variable
566
5.11 Common Programming Errors(1/3)
Do not confuse if and while statements
if statement implement a decision step
while/for statement implement a loop
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.
Remember to provide a prompt for the users, when
using a sentinel-controlled loop.
Make sure the sentinel value cannot be confused with
a normal data item.
567
Common Programming Errors (2/3)
Use do-while only when there is no possibility of
zero loop iterations.
Replace the segment with a while or for
statement when adding an if statement.
if (condition1)
do {
} while(condition1);
568
Common Programming Errors(3/3)
Do not use increment, decrement, or compound
assignment operators as subexpressions in
complex expressions.
Be sure that the operand of an increment or
decrement operator is a variable and that this
variable is referenced after executing the
increment or decrement operation.
569
Chapter Review (1)
Two kinds of loops occur frequently in
programming
Counting loops
The number of iterations required can be determined
before the loop is entered.
Sentinel-controlled loops
Repetition continues until a special data value is scanned.
570
Chapter Review (2)
Pseudocode for each form
Counter-controlled loop
Set loop control variable to an initial value of 0.
While loop control variable<final value
..
Increase loop control variable by 1
Sentinel-controlled loop
Get a line of data
While the sentinel value has not been encountered
Process the data line
Get another line of data
571
Chapter Review (3)
Pseudocode for each form
Endfile-controlled loop
Get first data value and save input status
While input status does not indicate that end of the file has
been reached
Process data value
Get next data value and save input status
Input validation loop
Get a data value
if data value isnt in the acceptable range,
go back to first step
572
Chapter Review (4)
Pseudocode for each form
General condition loop
Initialize loop control variable
As long as exit condition hasnt been met,
continue processing
C provides three statements for implementing
loops: while, for, do-while
The loop control variable must be initialized,
tested, and updated.
573
Question?
A good question deserve a good grade
574