An Object-Oriented Approach to Programming Logic and Design

advertisement
An Object-Oriented Approach to
Programming Logic and Design
Fourth Edition
Chapter 3
Making Decisions
Objectives
In this chapter, you will learn about:
• Evaluating Boolean expressions
• Relational comparison operators
• AND logic
• OR logic
• Making selections within ranges
• Precedence when combining AND and OR selections
An Object-Oriented Approach to Programming Logic and Design
2
Evaluating Boolean Expressions
• Selection structure (introduced in Chapter 2)
– Used when a program’s logic can take one of two paths
based on a decision
– Also called an if-then-else structure
• Example: driving directions
go North on Third Street
if Ninth Avenue is closed for repairs then
continue to Tenth Avenue and turn left
else
turn left on Ninth Avenue
endif
turn right on Sixth Street
An Object-Oriented Approach to Programming Logic and Design
3
Evaluating Boolean Expressions
(cont’d)
• Boolean expression
– Value can only be true or false
• Every decision in a computer program involves evaluating
a Boolean expression
• True/false evaluation is “natural” for a computer
– Computer circuitry consists of two-state on/off switches
– Each state is represented by a 1 or a 0
– Every computer decision yields true or false, yes or no
An Object-Oriented Approach to Programming Logic and Design
4
Pseudocode:
• if starts the selection
Indent action taken when true
• Align else with if
Indent action taken when false
• Endif shows end of structure
Flowchart:
• Logic takes one of two paths
based on answer to question
• No matter which path taken,
logic continues
An Object-Oriented Approach to Programming Logic and Design
5
Dual-alternative selection
Single-alternative selection
• Logic flows to one of two
alternatives
• Mutually exclusive choices
(never to both)
• Action is required for only
one outcome
• Also called if-then
An Object-Oriented Approach to Programming Logic and Design
6
Business program using if-then-else
• Several variables and
constants declared
• After input data
retrieved, makes
decision about
hoursWorked value
Figure 3-3
An Object-Oriented Approach to Programming Logic and Design
Figure 3-3
7
Flowchart and pseudocode for
payroll program determining
dental insurance
Program uses stacked structures,
one “on top of” and completely
separate from each other
Figure 3-4
An Object-Oriented Approach to Programming Logic and Design
Figure 3-4
8
Using Relational Comparison
Operators
• Three types of operations in a Boolean expression
– Both values equal
– First value greater than second value
– First value less than second value
• Relational operators
– Used to create Boolean
expressions
– Require two operands
An Object-Oriented Approach to Programming Logic and Design
Relational Operators
Operator
Name
==
Equivalency operator
>
Greater-than operator
<
Less-than
>=
Greater-than or equal-to operator
<=
Less-than or equal-to operator
<> or !=
Not-equal-to operator
9
Using Relational Comparison
Operators
•
•
•
•
Usually both operands are the same type
Expression evaluates to true or false
Can compare strings as well as numbers
Can compare variables and constants
An Object-Oriented Approach to Programming Logic and Design
10
Using the Relational Comparison
Operators (cont’d)
• Any relational situation can be expressed using three
types of comparisons: equal, greater than, and less
than
• Example: code in the two boxes is equivalent
if a >= b is True, then a < b is False
if a >= b is False, then a < b is True
An Object-Oriented Approach to Programming Logic and Design
11
Using Relational Comparison
Operators (cont’d)
• Using “not equal to” in decisions
– More prone to logical programming errors
– Different in various languages
Figure 3-5
An Object-Oriented Approach to Programming Logic and Design
12
Using Relational Comparison
Operators (cont’d)
• Most programming languages support a NOT
operator
– Reverses the meaning of a Boolean expression
– Unary operator: used in front of a single expression
– Example:
age <> 21
NOT (age – 21)
An Object-Oriented Approach to Programming Logic and Design
13
Using Relational Comparison
Operators (cont’d)
• Eliminate double negative
– Positive equivalent is more clear
Figure 3-6
An Object-Oriented Approach to Programming Logic and Design
14
Using the Wrong Relational
Operator
• Common error: choosing wrong operator
– Using > when >= is what is really desired
– All cases of = will be missed if this error is made
– Best to double-check intended meaning with the person
who requested the program
• Phrases that can cause misunderstandings
– No more than
– At least
– Not under
An Object-Oriented Approach to Programming Logic and Design
15
Understanding AND Logic
• Compound condition
– More than one selection structure to make decision
– Multiple questions before determining outcome
• AND decision
– Requires both conditions to be true for action to occur
– Can be constructed using nested decision
• Also known as a nested selection or nested if
• Nested decision contains a decision “inside of” another
decision
An Object-Oriented Approach to Programming Logic and Design
16
Flowchart pseudocode for cell
phone billing program
• Second decision falls within one
branch of the first decision
• Outer selection: first selection of
nested statements
• Inner selection: second selection
Figure 3-7
An Object-Oriented Approach to Programming Logic and Design
Figure 3-7
17
Nesting AND Decisions for
Efficiency
• When nesting decisions, must decide which is first
• With AND, result is the same no matter which is first
• Choosing the right decision to put first can improve
program performance
– First ask the question that is less likely to be true
• May eliminate or reduce second question evaluation
• May result in faster program execution
An Object-Oriented Approach to Programming Logic and Design
18
Using the AND Operator
• Conditional AND operator (AND operator)
– Evaluate two or more expressions in single statement
– One or more AND operators combine two or more
Boolean expressions
– True evaluation requires each Boolean expression be
true
An Object-Oriented Approach to Programming Logic and Design
19
Using the AND Operator
• Truth tables
– Diagrams used in mathematics and logic
– Describes truth of an
entire expression
• Truth based on the
truth of each part
• Short-circuit evaluation
— Evaluates each expression using an AND operator
— Evaluates only as far as necessary to determine whether
entire expression is true or false
An Object-Oriented Approach to Programming Logic and Design
20
Figure 3-9
An Object-Oriented Approach to Programming Logic and Design
• Computer
executes both
flowcharts in
Figure 3-9 in the
same manner
• Computer makes
decisions one at
a time in the
order they are
given
• In an AND
expression, if first
test is false,
entire expression
is false and
second test is not
performed
21
Avoiding Common Errors
in an AND Selection
• Common errors when making AND selections
– When AND selections are nested incorrectly
• Performing an action when only one condition is
satisfied
• Performing an action twice that should only occur once
– Failing to include a complete Boolean expression on
both sides of the operator
An Object-Oriented Approach to Programming Logic and Design
22
When satisfying two or
more criteria to initiate an
event, ensure that the
second decision is
nested entirely within the
first
Figure 3-10
An Object-Oriented Approach to Programming Logic and Design
23
Avoiding Common Errors
in an AND Selection
• Must provide a complete Boolean expression on
each side of the operator
• Example of valid compound expression
callMinutes > 100 AND callMinutes < 200
• Example of invalid compound expression
callMinutes > 100 AND < 200
An Object-Oriented Approach to Programming Logic and Design
24
Understanding OR Logic
• Conditional OR operator (OR decision)
– Take action if one of two conditions is true
– Requires at least one decision evaluated to be true
– If answers to both halves of question are false, entire
expression value is false
• Writing OR decisions
– Can choose to ask either question first
– First ask question that is more likely to be true
– May result in faster program execution
An Object-Oriented Approach to Programming Logic and Design
25
Flowchart and
pseudocode for cell
phone billing program
• Customer must meet
one or both of two
criteria to be billed a
premium
Figure 3-11
An Object-Oriented Approach to Programming Logic and Design
26
Two ways to assign a
premium to bills
of customers who meet
one of two criteria
Figure 3-12
Which program is more
efficient depends on the
relative likelihood of each
condition
Figure 3-12
An Object-Oriented Approach to Programming Logic and Design
27
Using the OR Operator
• Conditional OR operator (OR operator)
– Two or more questions in single comparison
– One condition must be met for resulting action to occur
• Short-circuiting
– If first question is true, logic does not proceed to second
question
• Truth table for OR operator
Table 3-3
An Object-Oriented Approach to Programming Logic and Design
28
• Computer executes both flowcharts
in the same manner
• Computer makes decisions one at a
time in the order they are given
• In an OR expression, If
first test is true, entire
expression is true and
second test is not
performed
Figure 3-13
An Object-Oriented Approach to Programming Logic and Design
29
Avoiding Common Errors
in an OR Selection
• Common errors when using OR operator
– Creating unstructured logic
• True and false decision paths must rejoin before
proceeding to the next steps in the program
– Using AND logic when OR logic is needed
• Often, a casual request for A and B logically means a
request for A or B
• Need to clarify what is really being requested
– Using OR logic when AND logic is needed
An Object-Oriented Approach to Programming Logic and Design
30
Avoiding Common Errors
in an OR Selection (cont’d)
• Unstructured flowchart for determining customer
cell phone bill
Figure 3-14
An Object-Oriented Approach to Programming Logic and Design
31
Avoiding Common Errors
in an OR Selection (cont’d)
• Example of using AND logic when OR logic is needed
Figure 3-15
An Object-Oriented Approach to Programming Logic and Design
32
Avoiding Common Errors
in an OR Selection (cont’d)
• Correct logic that gives a discount for young and old
movie patrons
Figure 3-16
An Object-Oriented Approach to Programming Logic and Design
33
Avoiding Common Errors
in an OR Selection (cont’d)
Incorrect logic that attempts
to charge full price for
patrons whose age is over
12 and under 65
Figure 3-17
An Object-Oriented Approach to Programming Logic and Design
34
Avoiding Common Errors
in an OR Selection (cont’d)
Correct logic that charges
full price for patrons whose
age is over 12 and under 65
Figure 3-18
An Object-Oriented Approach to Programming Logic and Design
35
Making Selections within Ranges
• Range of values
– Series of contiguous values that fall between specified limits
• Range check
– Compares variable to series of values between limits
• Use range check to make
comparisons using either lowest or
highest value in each value range
• Example: customer discount based
on number of items ordered
An Object-Oriented Approach to Programming Logic and Design
Items
Ordered
Discount
Rate (%)
0 to 10
0
11 to 24
10
25 to 50
15
51 or more 20
36
Flowchart and pseudocode of logic that selects
correct discount based on items ordered
In pseudocode, notice how
each if, else, and
endif group aligns
vertically
Figure 3-20
An Object-Oriented Approach to Programming Logic and Design
37
Avoiding Common Errors
when Using Range Checks
• Two common errors when using range checks
– Using logic that contains an unreachable path
– Asking questions when the answers are irrelevant
• Program may work correctly but is inefficient and
confusing
• Examples of both types of errors follow
An Object-Oriented Approach to Programming Logic and Design
38
• Inefficient range
selection that
includes an
unreachable path
• Programmer has
asked one question
too many
Figure 3-21
An Object-Oriented Approach to Programming Logic and Design
39
• Inefficient range
selection that
includes two
unnecessary
questions
• Wasting computer
time asking a
question that has
already been
answered
Figure 3-22
An Object-Oriented Approach to Programming Logic and Design
40
Understanding Precedence when
Combining AND and OR Operators
• Most languages allow multiple AND and OR operator
combinations in an expression
• When AND and OR are in the same statement, AND
operator takes precedence
• To control which operations are evaluated first:
– Use parentheses to override default order of operations
– Use parentheses for clarity
– Use nested if statements instead of ANDs and ORs
• Example of using nested if follows
An Object-Oriented Approach to Programming Logic and Design
41
Nested decisions that
determine movie patron
discount
Figure 3-23
An Object-Oriented Approach to Programming Logic and Design
42
Summary
• All decisions evaluate Boolean expressions
• Can compare any two values of the same type using
relational comparison operators
• AND decision
– requires both conditions to be true to return true result
– first ask question less likely to be true
• OR decision
– requires at least one condition be true to return true result
– first ask question more likely to be true
An Object-Oriented Approach to Programming Logic and Design
43
Summary (cont’d)
• Range checks
– Make comparisons with either lowest or highest value in
each range
– Avoid unnecessary or previously answered questions
• AND operators have higher precedence than OR
operators
An Object-Oriented Approach to Programming Logic and Design
44
Download