problem solving with decision structure
Embed Size (px)
TRANSCRIPT
-
7/31/2019 Problem Solving With Decision Structure
1/35
1
The Decision Logic Structure
Chapter 6
-
7/31/2019 Problem Solving With Decision Structure
2/35
2
IntroductionOutside of Sequential Logic,Decision Logic is the most used in
solutionsDecision Logic allows the programto react to different situations inthe data at runtime.
Decisions are made based on acondition(s) being true or false.
-
7/31/2019 Problem Solving With Decision Structure
3/35
3
The Structure of Decision
Logic in Computer LanguagesIf (something is true)
then
do statements that should be done ifthe condition is
else
do statements that should be done if
the condition isOnly one section of the decisionstatement is ever run in one executionof the containing program
-
7/31/2019 Problem Solving With Decision Structure
4/35
4
The Condition ExpressionMay only return True or False
Uses the or
a combination of the relationaloperators and the logic operators
The allow theprogrammer to make more thanone condition to be satisfied beforethe true or false block is selected
-
7/31/2019 Problem Solving With Decision Structure
5/35
5
What to Test?The exact nature/values of thetest(s) in the conditional
expression(s) are determinedduring problem analysis.
In C++ the construct is used to implement
decisions in the implementation ofthe solution.
-
7/31/2019 Problem Solving With Decision Structure
6/35
6
Programs must often anticipate
a variety of situations.
For example, ATMs must servevalid bank customers. They mustalso reject invalid PINs. The codethat controls an ATM must permit
these different requests. Softwaredevelopers must implement codethat anticipates all possibletransactions.
-
7/31/2019 Problem Solving With Decision Structure
7/357
The if Statement
General form:
if ( Conditional-expression )
true-part ;
The (Conditional-expression) is any
expression that evaluates to
either true or false.CondExpression: Value:
int hours = 40;
is hours > 40 No/ False
is hours >= 40 Yes/True
is hours < 40 No/ Falseis hours
-
7/31/2019 Problem Solving With Decision Structure
8/35
-
7/31/2019 Problem Solving With Decision Structure
9/359
Conditional/Logical
expressionsRelational Meaning
Operators
< Less Than
> Greater than
= Greater than or equal to
-
7/31/2019 Problem Solving With Decision Structure
10/3510
== // Exactly equal to
!= // Not equal to
4 == 4 ___________ // true (1) or false (0)
4 != 4 ___________
4 = 60.0)
cout
-
7/31/2019 Problem Solving With Decision Structure
11/3511
The if...else StatementThe if...else statement allows two alternate courses
of action.
The logical expression is evaluated to 0 (false) or a
nonzero (true) value. When true, the true-part is executedand the false-part is disregarded. When the logicalexpression is false, the false-part executes.
Logical Expression
True (non zero)
statement
statement
statement
statement
False (zero)
True-partFalse-part
-
7/31/2019 Problem Solving With Decision Structure
12/3512
The if...else Statement
if (logical-expression)
{
true-part ;
}
else
{
false-part ;
}
-
7/31/2019 Problem Solving With Decision Structure
13/35
13
(miles > 24000)
cout
-
7/31/2019 Problem Solving With Decision Structure
14/35
14
The Compound Statement in C++
{statement-1 ;
statement-2 ; //The compound statement
// (block)...
statement-N ;
}
-
7/31/2019 Problem Solving With Decision Structure
15/35
15
The compound statement groups togethermany statements as one.
( PINFound == true && NameValid == true)// Note: This true-part is a compound statement
// Process a balance query
Balance= Balance - WithdrawAmount;
// Using { } with 1 statement is unnecessary, yetconsistent
cout
-
7/31/2019 Problem Solving With Decision Structure
16/35
16
Common Selection Statement Errors
if(GPA >= 3.5)
// The true-part is the cout only
cout
-
7/31/2019 Problem Solving With Decision Structure
17/35
17
Logical Operators in C++
Expression Result Expression Result Expression Result ! 0 1 1 || 1 1 1 && 1 1
! 1 0 1 || 0 1 1 && 0 0
0 || 1 1 0 && 1 0
0 || 0 0 0 && 0 0
-
7/31/2019 Problem Solving With Decision Structure
18/35
18
Example
if((test >= 0) && (test
-
7/31/2019 Problem Solving With Decision Structure
19/35
19
Evaluate expression with relational and logicaloperators. Is test between 0 and 100 inclusive (leftcolumn)? Is test outside the range of 0 and 100inclusive (right column)?
(test >= 0) && (test 100)
( 97 >= 0) && ( 97 100)
1 && 1 0 || 01 Yes/ 0 No/
Relational and Logical Operators Combined
-
7/31/2019 Problem Solving With Decision Structure
20/35
20
Short Circuit Evaluation
// If E1 is false, E2 is not
// evaluated// If E1 is true, E2 is not
// evaluated
// Could we get an error ____?//Would it be possible to take the sqrt of a
negative number in the evaluation ofthis expression?
-
7/31/2019 Problem Solving With Decision Structure
21/35
21
Straight-through LogicAll decisions are processed one ata time in sequence
No false sections are included
All the decisions are consideredand the true statements areexecuted when the condition istrue
When a condition is false theprogram goes on to the nextdecision.
if(Guess < Num)
cout Num)
cout
-
7/31/2019 Problem Solving With Decision Structure
22/35
22
Positive Logic
False conditionalexpressions lead toadditional decisionswhich if False, allowfor more decisions tobe made, until aTrue is encounteredwhich is a signal to
go on to the nextdecision in asequence ofdecisions.
if(NotInArea == true)
cout
-
7/31/2019 Problem Solving With Decision Structure
23/35
23
Negative Logic
True conditionalexpressions lead to
additional decisions which if
True, allow for more
decisions to be made, until
a False is encountered
which is a signal to go on to
the next decision(s) if they
exist in a sequence of
decisions.
if(Money > 20)
{
if(Gas == true)
{
if(CarStart == true)
{
if(FriendAvail == true)
cout
-
7/31/2019 Problem Solving With Decision Structure
24/35
24
Nested LogicNested logic is one control structure containing
another similar control structure. An if...elseinside another if...else. e.g. (the 2nd if is placed onthe same line as the 1st):
if(GPA < 3.5)
cout
-
7/31/2019 Problem Solving With Decision Structure
25/35
25
More Nested LogicGiven the following
scale:
Value of C Output
34 C Hot20 C < 34 Warm
12 C < 20 Mild
0 C < 12 Cold
C < 0 Freezing
Complete this nested
if..else to show the
appropriate message
if(c >= 34)cout = 20)cout
-
7/31/2019 Problem Solving With Decision Structure
26/35
26
Which Decision Logic to Use
Evaluate all three types and make a decisionMost readableRequires the fewest tests
Easiest to maintain
My experience is that the problem will hint atwhich is best. Example:
(Success == true) Do Lots of stuff like the rest of the program
This means the else will be at the bottom of the program
Put out a warning message.
(Success == false) Put out warning message
Put the rest of the program here.
-
7/31/2019 Problem Solving With Decision Structure
27/35
27
Logic ConversionThis means converting from positive tonegative logic or negative to positive logic
Change < to >=
Change > to = to 20) ---> may be T or F
(Gas in Car) --> may be T or F
(Friend Avail) --> may be T or F
There are 8 possible combinations of thesethree conditions
See Next Slide
-
7/31/2019 Problem Solving With Decision Structure
30/35
30
A Decision Table
Conditions Possible Combinations(Money > 20) T T T T F F F F
(Gas in Car) T T F F T T F F
(Friend Avail) T F T F T F T F
Dinner Out X
Go To Bank X X X X
Get Gas X X
Eat At Home X X X X X X X
The goal is to go out to dinner with a friend. Before one can do
this, I must have $20 or more, Gas in the car, and my friend must
be available. Otherwise, I must correct some problems and eat at
home.
A
CT
I
O
N
S
-
7/31/2019 Problem Solving With Decision Structure
31/35
31
Decision Logic for NowAll programs use some sort of decision logic.
Whether it is Positive or Negative decision logicis generally irrelevant
The important thing is to correctly capture allthe possible solutions decision situations andassociate them with the proper outcomes.
Proper Testing insures that all potentialsituations are accounted for!
In C++ the if()else construct is the primarydecision making facility.
-
7/31/2019 Problem Solving With Decision Structure
32/35
32
Some examplesThe following slides give you someexamples of C++ programs using if
logic
-
7/31/2019 Problem Solving With Decision Structure
33/35
33
// Filename: AGETEST.CPP
// Helps ensure age values are reasonable.
#include
using namespace::std;
void main()
{
int age;
cout > age;
if (age >=16)
{cout
-
7/31/2019 Problem Solving With Decision Structure
34/35
34
// Filename: IFELSE1.CPP
// Demonstrates if-else by printing whether an
// input value is greater than zero or not.#include
void main()
{
int num;
cout > num; // Get the user's number.
if (num > 0)
{
cout
-
7/31/2019 Problem Solving With Decision Structure
35/35
// Filename: SERV.CPP
// Prints a message depending on years of service.
#include
void main()
{
int yrs;
cout > yrs; // Determine the years they have worked.
if (yrs > 20)
{cout 10)
{
cout