An Object-Oriented Approach to Programming Logic and

Download Report

Transcript An Object-Oriented Approach to Programming Logic and

An Object-Oriented Approach to
Programming Logic and Design
Fourth Edition
Chapter 4
Looping
Objectives
In this chapter, you will learn about:
• The loop structure
• Using a loop control variable
• Nested loops
• Avoiding common loop mistakes
• Using a for loop
• Common loop applications
An Object-Oriented Approach to Programming Logic and Design
2
Understanding the Loop Structure
• Looping
– Makes computer programming efficient and useful
– One set of instructions can operate on multiple data
sets
An Object-Oriented Approach to Programming Logic and Design
3
Understanding the Loop Structure
(cont’d)
• Loop body
– Statements within a loop
• Loop structure
– One of three basic structures in structured programming
– Starts with a test of a Boolean expression
– Executes as long as Boolean expression is true
• Referred to as repetition, iteration, or while loop
An Object-Oriented Approach to Programming Logic and Design
4
Understanding the Loop Structure
(cont’d)
• Example of a while loop
while quantity in inventory remains low
continue to order items
endwhile
• endwhile signals where loop structure ends
• Structured loop has one entry and one exit point
• Body of loop can contain any number of statements
– includes sequences, selections, and other loops
An Object-Oriented Approach to Programming Logic and Design
5
Using a Loop Control Variable
• Loop control variable
– Value is tested to control loop’s execution
• Three actions occur
– Initialize loop control variable before entering loop
– Test loop control variable
• If true, enter loop body
– Alter loop control variable value in loop body
• So that while expression eventually evaluates false
An Object-Oriented Approach to Programming Logic and Design
6
Using a Loop Control Variable
(cont’d)
• Need to control number of repetitions
– An infinite loop has no end
• Ways to control repetitions
– Use a counter to create a definite (counter-controlled)
loop
– Use a sentinel value to create an indefinite loop
An Object-Oriented Approach to Programming Logic and Design
7
Using a Definite Loop with a Counter
• Definite loop
– Executes a predetermined number of times
– Also called a counted loop or counter-controlled loop
• Counter
– Numeric variable to count event occurrence
– Variable usually initialized to 0
• Example: Figure 4-2 on next slide
An Object-Oriented Approach to Programming Logic and Design
8
• Using a definite loop
with a counter
• Control variable initialized to 0
• while expression compares
count to 4
• Value of count < 4, so loop
body executes
• Displays “Hello” and adds 1 to
count
• Next time count is evaluated,
its value is 1
• Loop body executes again, and
count becomes 2
• After four times, count < 4
is false, loop ends
An Object-Oriented Approach to Programming Logic and Design
9
Using a Definite Loop with a Counter
(cont’d)
• Methods of changing loop control variable
– Incrementing
• Adds to variable
– Decrementing
• Reduces variable
• Test whether value remains greater than a benchmark value
An Object-Oriented Approach to Programming Logic and Design
10
Using An Indefinite Loop
with a Sentinel Value
• Indefinite loop
– Loop execution time based on user input
– Loop may be performed different number of times each
time program runs
• Priming input
– First input that sets loop control variable’s first value
• Sentinel value
– Value that signals a stop to a loop
• Figure 4-3 on following slide illustrates an indefinite
loop
An Object-Oriented Approach to Programming Logic and Design
11
• An application
with an indefinite loop
Figure 4-3
An Object-Oriented Approach to Programming Logic and Design
12
Using Nested Loops
• Nested loops
– A loop inside of another loop
– Outer loop: loop that contains the other loop, or inner
loop
– Used when two or more variable values repeat to produce
every combination of values
An Object-Oriented Approach to Programming Logic and Design
13
Example: Creating a
quiz answer sheet
using a nested loop
An Object-Oriented Approach to Programming Logic and Design
14
Avoiding Common Loop Mistakes
• Four common 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
An Object-Oriented Approach to Programming Logic and Design
15
Mistake: Neglecting to Initialize
the Loop Control Variable
• Always a mistake
• Uninitialized variables may contain unknown values in
some programming languages
• Program logic errors will occur
• Figure 4-7 (next slide) shows the correct logic for a
greeting program
• Figure 4-8 (slide after next) shows an example of a
program where the loop control variable is not initialized
An Object-Oriented Approach to Programming Logic and Design
16
Correct logic for greeting
program
•Prompts user for a name
•While name continues to
be anything but the value
“ZZZ”, the program outputs a
greeting and asks for the
next name
Figure 4-7
An Object-Oriented Approach to Programming Logic and Design
17
Incorrect logic for
greeting program
•Missing loop control
variable initialization
Figure 4-8
An Object-Oriented Approach to Programming Logic and Design
18
Mistake: Neglecting to Alter
the Loop Control Variable
• Can cause a variety of errors, such as an infinite loop
• Figure 4-9 (next slide) provides an example of this
common mistake
– No names are accepted inside the loop
An Object-Oriented Approach to Programming Logic and Design
19
Incorrect logic for
greeting program
•Loop control variable is
not altered
Figure 4-9
An Object-Oriented Approach to Programming Logic and Design
20
Mistake: Using the Wrong Comparison
with the Loop Control Variable
• Correct operators and operands must be used
• Could also result in wrong number of loop executions
• Figure 4-10 (next slide) shows an example of this
common mistake
An Object-Oriented Approach to Programming Logic and Design
21
Incorrect logic for program
•Wrong test is made with the
loop control variable
•Greater-than comparison is
made instead of not-equal-to
comparison
•Loop is never entered and
program ends
Figure 4-10
An Object-Oriented Approach to Programming Logic and Design
22
Mistake: Including Statements inside
the Loop that Belong outside the Loop
• Can cause a program to perform inefficiently by
unnecessarily executing the same code numerous times
• Figure 4-11 (next slide) demonstrates an inefficient way
to produce 100 discount stickers for items
– Inefficient because newPrice is calculated 100 times
even though price hasn’t changed
• Figure 4-12 shows an improved method
An Object-Oriented Approach to Programming Logic and Design
23
Inefficient way to
produce 100 discount
stickers for differently
priced items
• newPrice is
calculated 100 times
even though price hasn’t
changed
Figure 4-11
An Object-Oriented Approach to Programming Logic and Design
24
Figure 4-11
An Object-Oriented Approach to Programming Logic and Design
25
Improved version of program
• newPrice is calculated once per
new price; the calculation is moved to
a better location
• Program performs more efficiently
Figure 4-12
An Object-Oriented Approach to Programming Logic and Design
26
Figure 4-12
An Object-Oriented Approach to Programming Logic and Design
27
Using a for Loop
• The for loop
– Alternative to while loop
– Used when the program knows exactly how many times
the loop will repeat
• Three actions in one compact statement
– Initializes loop control variable
– Evaluates loop control variable
– Alters loop control variable
• for statement looks different in various languages
An Object-Oriented Approach to Programming Logic and Design
28
Using a for Loop (cont’d)
• Three possible ways to write pseudocode to display Hello
four times using for and while loops
Figure 4-13
An Object-Oriented Approach to Programming Logic and Design
29
Using a for Loop (cont’d)
• Step value
– The amount by which the loop control variable changes
after the body executes
– Can be positive or negative
– Does not have to be 1
• Step value example: Displays “Hello” four times
for count = 12 to 6 step -2
output “Hello”
endfor
An Object-Oriented Approach to Programming Logic and Design
30
Common Loop Applications
• Every computer program is different
– Various applications use similar techniques
– Loops can be used to:
• Accumulate totals
• Validate data
An Object-Oriented Approach to Programming Logic and Design
31
Using a Loop to Accumulate Totals
• Business reports often include totals
– Example: report of total value for real estate properties
sold in the last month
• Accumulator
– Variable used to gather or accumulate values during
repetitions
– Must be initialized prior to entering loop
– Value added to current value during each repetition
– Value is output at end of processing
• Example: Figure 4-15 on next slide
An Object-Oriented Approach to Programming Logic and Design
32
• Flowchart and pseudocode for
real estate sales report
program
Figure 4-15
Figure 4-15
An Object-Oriented Approach to Programming Logic and Design
33
Using a Loop to Validate Data
• Defensive programming
– prepare for all possible errors before they occur
• Can use loops to validate data
– Make sure data is meaningful and useful
– Could involve checking data type or range
• Example program: user enters birth month number
– Possible actions if input is less than one or greater than 12
• Display error message and stop the program
• Assign default value for month before proceeding
• Reprompt user for valid input
– See Figure 4-16 on next slide
An Object-Oriented Approach to Programming Logic and Design
34
• Reprompting
user once after
an invalid month
is entered
• User still may
enter invalid
data
• Better to use a
loop to prompt
until user enters
valid data
Figure 4-16
An Object-Oriented Approach to Programming Logic and Design
35
Limiting a Reprompting Loop
• Reprompting
– Can help ensure invalid data
– May frustrate or annoy the user if it is continuous
• Good programming practice
– State the valid values in the prompt
– Limit the number of attempts
– Force (override) the input to a specific value after a certain
number of attempts
• Example: Figure 4-18 on next slide
An Object-Oriented Approach to Programming Logic and Design
36
• Program limits the
number of times the
user can input the
month of their birth
Figure 4-18
An Object-Oriented Approach to Programming Logic and Design
37
Validating a Data Type
• Validating date requires a variety of methods
• Some programming languages have prewritten
methods to check data type
– Examples:
•
•
•
•
isNumeric()
isChar()
isWhitespace()
isUpper()
• Example: Figure 4-19 on next slide
An Object-Oriented Approach to Programming Logic and Design
38
Sample program:
Checking data for
correct type
•Uses method
isNumeric() to
determine if the user’s
input is a number
•Reprompts the user
until input is a number
Figure 4-19
An Object-Oriented Approach to Programming Logic and Design
39
Validating Reasonableness and
Consistency of Data
• Good programming practice to validate data
– Valid data is not necessarily correct
– The more accurate the data, the more useful the output
• Examples of checks that can be made
– Compare zip code with city
– Compare date of a purchase and date of payment
– If a customer’s title is “Ms.,” gender should be “F”
An Object-Oriented Approach to Programming Logic and Design
40
Summary
• When a loop is used in a computer program, one set of
instructions operates on multiple, separate sets of data
• Three steps must occur (in every loop)
– Initialize loop control variable
– Compare control variable to value determining when loop
stops
– Alter the loop control variable
• Nested loops are loops within loops; two control
variables are used and altered at the appropriate time
An Object-Oriented Approach to Programming Logic and Design
41
Summary (cont’d)
• Common loop mistakes
–
–
–
–
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
• for statement: used with definite loops
– Uses a loop control variable that is automatically
initialized, evaluated and incremented
• Loops: used in many applications to accumulate data and
to ensure that user data entries are valid and reasonable
An Object-Oriented Approach to Programming Logic and Design
42