pld7e_ch05

advertisement
Objectives
• In this chapter, you will learn about:
– Counter-controlled and sentinel controlled loops
– Nested loops
– Using a for loop
– Common loop applications
– Loop control structure in RAPTOR
• repeat until true rather than repeat while true
1
Understanding the Advantages of Looping
• Loop:
– control structure that repeats a set of actions (loop body)
while some condition remains true or until some condition
becomes true.
2
Loop Control Structure in RAPTOR
In RAPTOR: you repeat the body of the
loop UNTIL the condition evaluates to
true.
RAPTOR lets you structure your loop as
one of three types:
1.
2.
3.
RAPTOR Loop Symbol
Pre-Test loop
Mid-Test loop
Post-Test loop
( while / for )
illegal in our book
( do … while )
Our book only shows us pre-test loops.
Note: In most languages (including Java) you repeat the loop body while the condition remains true
3
Figure 5-1
The loop structure (pre-test loop)
Our book calls this a while loop
4
Looping
Definite and Indefinite Loops
Looping may be achieved using either a definite loop or an indefinite
loop
• A definite loop is also referred to as a counter-controlled loop
• An indefinite loop is also referred to as a sentinel-controlled loop
• For a definite loop, the loop body will be executed a specific
number of times.
• For an indefinite loop, the number of times the body of the loop
should be executed can be different for each run of a program
5
Using a Counter-Controlled while loop
• As long as a boolean expression (the condition) remains
true, the while loop’s body executes.
– RAPTOR keep executing UNTIL the condition becomes true
• Essential Steps:
– Create and initialize a loop control variable (lcv)
– Determine the upper or lower limit for the lcv
– Determine the step (increment or decrement) for the lcv
– Determine the boolean expression (condition) that will control
the loop
– Each iteration of the loop, update the lcv
6
Using a Definite (Counter-Controlled) Loop
Must the
condition be
true or false for
the loop body
to be executed?
In RAPTOR,
what would the
condition be?
How many
times is “Hello”
displayed?
lcv is: count
Figure 5-3
7
A counter-controlled while loop
Using an Indefinite Loop (Sentinel-Controlled) with a
Sentinel Value
• Indefinite loop
– May be performed a different number of times each time the program executes
• Essential steps:
– Identify a sentinel value (value outside the range of valid input data) that will be
used as the loop exit condition
• name = QUIT
//where QUIT is a named constant sentinel value
• End_of_input
//RAPTOR sentinel module expression
• Java  hasNext( ) == false
//Java method to evaluate end of input condition
– Each iteration of the loop get a new input value to compare to the sentinel value.
8
Must the
condition be
true or false for
the loop body
to be executed?
In RAPTOR,
what would the
condition be?
Figure 5-4 An indefinite while loop that displays “Hello” as long as the user wants to continue
9
Understanding the Loop in a Program’s
Mainline Logic
• Three steps that should occur in every properly
functioning loop
– Initialize the variable that will control the loop
( sentinel or counter value )
– Test the condition to determine whether the loop body
executes
– Update (aka alter) the loop control variable
• increment/decrement the lcv
• get a new input value to compare to the sentinel value
10
Nested Loops
• Nested loops:
– loop within another loop
• 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
11
Must the
condition be
true or false for
the loop body
to be executed?
In RAPTOR,
what would the
condition be?
RAPTOR / Java
<= versus >
= versus !=
>
versus <=
“flip” the
operator!
12
Figure 5-8
Flowchart and pseudocode for AnswerSheet program
Common Loop Mistakes
• Neglecting to initialize the loop control variable
• Neglecting to update the loop control variable
• Loop executes one too many or one too few times
– operator: < or <=
– number of iterations =
OR
> or >=
Last used – First used + 1
• Including statements inside the loop that belong
outside the loop
13
Figure 5-10
14
Incorrect logic for greeting program because the loop control variable initialization is missing
Figure 5-10
Incorrect logic for greeting program because the loop control variable is not altered
Programming Logic & Design, Sixth Edition
15
For a
sentinelcontrolled loop
the only
operators you
should use in
the condition
are = or !=
Figure 5-12 Incorrect logic for greeting program because the wrong test is used in the condition
Programming Logic & Design, Sixth Edition
16
Avoiding Common Loop Mistakes
(continued)
• Mistake:
– including statements inside the loop that belong outside
the loop
• Example:
– discount every item by 30 percent
– Inefficient because the same value is calculated 100
separate times for each price that is entered
– Move outside loop for efficiency
17
Figure 5-13 Inefficient way to produce 100 discount price stickers for differently priced items
18
Figure 5-14
19
Improved discount sticker-making program
Using a for Loop
• for statement or for loop is a definite loop
• specifically, it is a pre-test loop
• can be used in pseudocode or a Java program
• Remember, keywords like while, for, do have no meaning in a flowchart!
• Puts all of the loop control expressions in the for loop header
– Initialize
– Test
– Update
• Takes the form:
[initial, final]
for loopControlVariable = initialValue to finalValue [step stepValue]
do something
endfor
20
Using a for Loop (continued)
• Example pseudocode for loop
for count = 0 to 3 step 1
output “Hello”
end for
•
•
•
•
•
•
[0,3]
Initializes count to 0
Checks count against the limit value 3 (test)
If evaluation is true, for statement body prints the label
Executes 4 times ( last=3, first=0, 3-0+1 equals 4 )
Increases count by 1 (update)
while loop:
– count = 0
– while count <= 3
• Java for loop:
21
or
while count < 4
for ( count=0; count <= 3; count += 1 )
Using a for Loop (continued)
• while statement could be used in place of for
statement
• Step value:
– number used to increase (decrease) the 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 a value other than
1
22
Common Loop Applications
• Using a loop to count and accumulate totals
– Examples
•
•
•
•
Business reports often include totals
List of real estate sold and total value
Count of number of records processed
keep track of number of A’s, B’s, C’s, etc.
• Counters and Accumulators:
• Counter
• Accumulator
usually is incremented by one each iteration
has some value added to it each iteration
– Running sum
23
Common Loop Applications
• Accumulate total real estate prices
– Declare numeric variable at beginning to be used as an
accumulator
– Initialize the accumulator to 0
– Read each transaction’s data record
– Add its value to accumulator variable
– Keep reading records until eof is encountered
24
Common Loop Applications (continued)
5 records processed
Figure 5-16
25
Month-end real estate sales report
Figure 5-17 Flowchart and pseudocode for real estate sales report program
26
Common Loop Applications (continued)
• Use a loop to validate data
– When prompting a user for data, there is no guarantee
that
• Validate data:
– make sure data falls within an acceptable range
• Example: user enters birth month
– If number is 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
27
Figure 5-18 Reprompting a user once after an invalid month is entered
Programming Logic & Design, Sixth Edition
28
This test checks to
see if the user
entered a value
too small or too
large, that is, if
the value is
OUtSIDE of the
valid range.
In RAPTOR, the
test would be
month >=
LOW_MONTH
and month <=
HIGH_MONTH
Figure 5-19 Reprompting a user using a loop after an invalid month is entered
Programming Logic & Design, Sixth Edition
29
Common Loop Applications (continued)
• Validating a data type
– Validating data requires a variety of methods
– isNumeric() isChar() or isWhitespace()
• RAPTOR has a built-in procedure Is_number
• Your program may:
– Accept user data as a string
– Use a method to convert to correct to data type
30
Common Loop Applications (continued)
Figure 5-21 Checking data for correct type
31
RAPTOR test for invalid data
Programming Logic & Design, Seventh Edition
32
Common Loop Applications (continued)
• Validating reasonableness and consistency of data
– Many data items can be checked for reasonableness
– Good defensive programs try to foresee all possible
inconsistencies and errors
33
Summary
• Use a loop to:
– repeat a sequence of statements (RAPTOR symbols)
• Three steps must occur in every loop
– Initialize
– Test
input variable or loop control variable
variable
(evaluate condition)
– Update the variable that controls the loop
• Nested loops:
– loops within loops
34
Summary (continued)
• Common mistakes made by programmers
– Neglecting to initialize loop control variable
– Neglecting to update the loop control variable
– Using the wrong comparison with the 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 loop
– number of iterations is known
• while loop used with indefinite loop
– number of iterations is not known
35
Summary (continued)
• for loop expressions:
– Initialize
– Test
– Update
• Accumulator
– variable that accumulates values creating a running sum
• Counter
– Variable used to keep track of the number of occurrences
of something (records, customers processed, etc.)
• Loops are often used to ensure user data is valid
36
Download