Title: Programming Logic and Design Fifth Edition, Comprehensive
1Programming Logic and Design Fifth Edition,
Comprehensive
2Objectives
- Learn about the advantages of looping
- Control loops with counters and sentinel values
- Nest loops
- Learn to avoid common loop mistakes
3Objectives (continued)
- Use a for loop
- Use posttest loops
- Recognize the characteristics shared by all loops
- Learn about common loop applications
4Understanding the Advantages of Looping
- Looping makes computer programming efficient and
worthwhile - Write one set of instructions to operate on
multiple, separate sets of data - Loop structure that repeats actions while some
condition continues
5Understanding the Advantages of Looping
(continued)
Figure 5-1 The while loop
6Controlling Loops with Counters and Sentinel
Values
- As long as a Boolean expression remains true,
while loops body executes - Must control number of repetitions to avoid an
infinite loop - Repetitions controlled by
- Counter
- Sentinel value
7Using a Definite while Loop with a Counter
- Three actions make a while loop end correctly
- Loop control variable is initialized
- Prior to entering the loop
- Loop control variable is tested
- If result is true, loop body entered
- Loop control variable must be altered in loop
body - while expression eventually evaluates to false
- Loop control variables altered by
- Incrementing
- Decrementing
8Using a Definite while Loop with a Counter
(continued)
Figure 5-2 A while loop that prints Hello four
times
9Using a Definite while Loop with a Counter
(continued)
- Definite loop number of iterations predetermined
- Also called counted loop
- Counter numeric variable used to count number of
times an event occurs - Loop control variable may be altered by user
input - Indefinite loop loop iterates until some
condition is true - Number of iterations may vary
10Using an Indefinite while Loop with a Sentinel
Value
- Indefinite loop loop performed a different
number of times each time the program executes - Three crucial steps
- Starting value to control the loop must be
provided - Comparison must be made using the value that
controls the loop - Within the loop, value that controls the loop
must be altered - Loop control variable any variable that
determines whether the loop will continue
11Figure 5-3 Looping bank balance program
12Using an Indefinite while Loop with a Sentinel
Value (continued)
Figure 5-4 Typical execution of the looping bank
balance program
13Using an Indefinite while Loop with a Sentinel
Value (continued)
Figure 5-5 Crucial steps that must occur in
every loop
14Nested Loops
- Nested loops loops within loops
- Outer loop loop that contains the other loop
- Inner loop loop that is contained
- Needed when values of two (or more) variables
repeat to produce every combination of values
15Figure 5-7 Flowchart and pseudocode for
AnswerSheet program
16Mixing Constant and Variable Sentinel Values
- Number of times a loop executes can depend on a
constant or a value that varies - May not want to repeat every pass through a loop
the same number of times - Example
- Print 100 labels for every employee
- Outer loop controlled by value of employee name
- Inner loop executes 100 times
- Print variable number of labels for every
employee - Outer loop controlled by value of employee name
- Inner loop controlled by production level
17Mixing Constant and Variable Sentinel Values
(continued)
Figure 5-8 Program that produces 100 labels for
every employee
18Mixing Constant and Variable Sentinel Values
(continued)
Figure 5-8 Program that produces 100 labels for
every employee (continued)
19Figure 5-9 Program that produces a variable
number of labels for every employee
20Avoiding Common Loop Mistakes
- Neglecting to initialize the loop control
variable - Neglecting to alter the loop control variable
- Using the wrong comparison with the loop control
variable - Including statements inside the loop that belong
outside the loop
21Avoiding Common Loop Mistakes (continued)
- Mistake neglecting to initialize the loop
control variable - Example get name statement removed
- Value of name unknown or garbage
- Program may end before any labels printed
- 100 labels printed with an invalid name
- labelCounter 0 statement removed
- Value of labelCounter unpredictable
- Loop might not execute
- If automatically initialized to zero, only first
labels printed
22Figure 5-10 Incorrect logic when loop control
variable initializations are removed from
label-making program
23Avoiding Common Loop Mistakes (continued)
Figure 5-10 Incorrect logic when loop control
variable altering statements are removed from
label-making program (continued)
24Avoiding Common Loop Mistakes (continued)
- Mistake neglecting to alter the loop control
variable - Remove get name instruction from outer loop
- User never enters a name after the first one
- Inner loop executes infinitely
- Remove the statement that increments labelCounter
- Inner loop executes infinitely
- Always incorrect to create a loop that cannot
terminate
25Avoiding Common Loop Mistakes (continued)
- Mistake using the wrong comparison with the loop
control variable - Programmers must use correct comparison
- Off-by-one error
- Seriousness depends on actions performed within a
loop - Overcharge insurance customer by one month
- Overbook a flight on airline application
- Dispense extra medication to patients in pharmacy
26Avoiding Common Loop Mistakes (continued)
- Example
- Correct loop performed 10 times
- counter 0
- while counter lt 10
- print Hello
- counter counter 1
- end while
27Avoiding Common Loop Mistakes (continued)
- Example (continued)
- Error loop performed 11 times
- counter 0
- while counter lt 10
- print Hello
- counter counter 1
- end while
28Avoiding Common Loop Mistakes (continued)
- Mistake including statements inside the loop
that belong outside the loop - Example calculating a users projected weekly
pay raise - Value of weeklyPay recalculated on every pass
through the loop, although it does not change - Inefficient, especially for complicated
calculations or large numbers of calculations
29Figure 5-12 Pay rate projection program
30Figure 5-14 Improved pay rate projection program
31Using a for Loop
- for statement or for loop is a definite loop
- Provides three actions in one structure
- Initializes
- Evaluates
- Increments
- Takes the form
- for initialValue to finalValue
- do something
- endfor
32Using a for Loop (continued)
- Example
- for count 0 to 99
- print LABEL_TEXT, name
- endfor
- Initializes count to 0
- Checks count against the limit value 99
- If evaluation is true, for statement body prints
the label - Increases count by 1
33Using a for Loop (continued)
- while statement could be used in place of for
statement - Step value number used to increase a loop
control variable on each pass through a loop - Programming languages can
- Require a statement that indicates the step value
- Have a step value default of 1
- Specify step value when each pass through the
loop changes the loop control variable by value
other than 1
34Using Posttest Loops
- Loop body may never execute in while loop and for
loop - Use posttest loop when loop body must execute at
least once - do-until loop
- do-while loop
- do-until loop executes until condition is true
- do-while loop executes until condition is false
35Using Posttest Loops (continued)
Figure 5-15 Inner loop from label production
program in Figure 5-9
36Using Posttest Loops (continued)
Figure 5-16 Label production program using a
do-until loop
37Recognizing the Characteristics Shared by All
Loops
- Every logical problem could be solved using only
the while loop - Other forms are conveniences
- while loop
- Loop-controlling question placed at beginning of
steps that repeat - do-until loop
- Loop-controlling question placed at end of steps
that repeat
38Recognizing the Characteristics Shared by All
Loops (continued)
- Characteristics of all structured loops
- Loop-controlling question must provide entry or
exit from repeating structure - Loop-controlling question provides the only entry
to or exit from the repeating structure - Exactly one loop-controlling value
- Provides only entry to or exit from the loop
39Recognizing the Characteristics Shared by All
Loops (continued)
Figure 5-17 Examples of unstructured loops
40Common Loop Applications
- Using a loop to accumulate totals
- Examples
- Business reports often include totals
- Telephone bill provides a total
- List of real estate sold and total value
- Accumulator variable that gathers values
- Similar to a counter
- Counter increments by one
- Accumulator increments by some value
41Common Loop Applications (continued)
- Accumulate total real estate prices
- Declare numeric variable at beginning
- Initialize the accumulator to 0
- Read each transactions data record
- Add its value to accumulator variable
- Read the next record until eof
- Variables exist only for the life of the
application - Run the application a second time, variables
occupy different memory location
42Common Loop Applications (continued)
Figure 5-18 Month-end real estate sales report
43Figure 5-19 Flowchart and pseudocode for real
estate sales report program
44Common Loop Applications (continued)
- Using a loop to validate data
- When prompting a user for data, no guarantee that
data is valid - Validate data make sure data falls in acceptable
ranges - Example user enters birth month
- If number less than 1 or greater than 12
- Display error message and stop the program
- Assign default value for the month
- Reprompt the user for valid input
45Common Loop Applications (continued)
Figure 5-20 Reprompting a user once after an
invalid month is entered
46Common Loop Applications (continued)
Figure 5-21 Reprompting a user continuously
after an invalid month is entered
47Summary
- When using a loop, write one set of instructions
that operates on multiple, separate data - Three steps must occur in every loop
- Initialize loop control variable
- Compare variable to some value
- Alter the variable that controls the loop
- Nested loops loops within loops
- Nested loops maintain two individual loop control
variables - Alter each at the appropriate time
48Summary (continued)
- Common mistakes made by programmers
- Neglecting to initialize loop control variable
- Neglecting to alter loop control variable
- Using wrong comparison with loop control variable
- Including statements inside the loop that belong
outside the loop - Most computer languages support a for statement
- for loop used with definite loops
- When number of iterations is known
49Summary (continued)
- for loop automatically
- Initializes
- Evaluates
- Increments
- Use posttest loop when loop body must execute at
least one time - Control variable evaluated after loop body
executes
50Summary (continued)
- Characteristics of all structured loops
- Loop-controlling question provides entry or exit
from repeating structure - Loop-controlling question provides the only entry
or exit from repeating structure - Accumulator variable that gathers values
- Loops used to ensure user data is valid by
reprompting the user