```Intro to Programming
& Algorithm Design
Decisions
Decisions
Decisions
Assg
This presentation can be viewed on line in a file named:
ch04.IntrotoProg.ppt
1
Objectives

Explain
 Boolean
expressions
 Comparison
operators
 IF/THEN/ELSE
 AND
and OR logic
 Nested
 Case
logic
IFs
structure
2
Decision Structure

Up till now all instructions in a
module executed in sequence
 i.e.
Statements executed in order
from top to bottom

Decision structures allow
programmer to define the specific
condition(s) when a statement
should be executed
 Conditions
specified as Boolean
expressions
3
Boolean Expression

Results in a value of true or false

Most basic consists of
 Constant
Value or Variable
 Comparison Operator
 Constant Value or Variable

Examples
gender
= "F"
hoursWorked > 40
4
Boolean Expression

Values in expression can be a
variables or constants
In
both examples, the first value
was a variable and the second
was a constant
 But

it doesn't have to be that way
Most languages support the
following comparison operations
 Equal,
Not Equal
 Greater Than, Less Than
5
Boolean Expression

equal, greater than, and less
than to form
 Greater
Than or Equal
 Less Than or Equal

Different languages support
comparison operations with
different commands
 .equals
 EQ
 equal
6
Boolean Expression

Most support the algebraic symbols
>
- greater than
 < - less than
 >= - greater than or equal to
 <= - less than or equal to

Equal and Not Equal are a little
tricky
A
= 10 in many languages, assigns the
value 10 to the variable A
 A == 10 compares variable A to the
constant value 10
7
Boolean Expression

Not Equal often expressed as
 <>


- not equal
However Java, and the various
versions of C use !=
 Exclamation point means not
Examples
 state != "FL"
 isPrint = !true
 !(salary > 75000)
8
Boolean Expression

Negative logic can be confusing

Try not to use

 if

Use
 if

(!(salary > 75000))
(salary <= 75000)
Often, in programming languages,
the Boolean expression is enclosed
in ()
9
Boolean Expression


However sometimes the nonnegative logic is not viable
For instance, the alternative to
 state

!= "FL"
Would be 49 conditions, which
would be much more code and
therefore
 Less
efficient
 More likely to have errors
10
Boolean Expression

Can perform same selection
with different operators
If (price > limit) Then
finalCost = price * luxuryTax
Else
finalCost = price * salesTax
Endif
If (price <= limit) Then
finalCost = price * salesTax
Else
finalCost = price * luxuryTax
Endif
11
Boolean Expression

Which one is better?
 The
one that is more efficient
 The
one that causes the fewer number
of statements to be executed

How determine?
 Need
 Are
more than 50% of the prices over
or under the limit?
• If over limit, check price > limit first
• If under limit, check price <= limit first
12
Boolean Expression Gotcha


Must compare values of the
same type
 totalCost
== "Joe Smith"
 TotalCost
 gender
> 10
 Gender
 10
is a numeric variable
is a string variable
== "A"
 Comparing
a number to a string
13
Decision Structure


In pseudocode, use the word If
followed by a Boolean condition in
parenthesis
Statements to be executed if true
If (month == 1) Then
Display “Jan”
End If
If (month == 2) Then
Display “Feb”
End If
14
Boolean Expression
month
== 1
False
True

Display “Jan”

month
== 2
False
True
In flow charts, put
into diamond
symbol (selection)
Two logic paths
out of diamond
 True
Display “Feb”
 False
15
Java if Statement

Syntax of an if/else statement

if(boolean expression) { statements to
be executed if true }
if (month == 1) {
System.out.println(“Jan”);
}
if (month == 2) {
System.out.println(“Feb”);
}
16
Java if Statement

When comparing a String variable
must use .equals
String gender;
:
:
if (gender.equals(“f”)) {
System.out.println(“Female”);
}
if (gender.equals(“m”)) {
System.out.println(“Male”);
}
17
Dual Alternative Decision


Can specify what should happen if
condition is false
In pseudocode, use the word Else
and indent statements to be
executed if false
If (gender == “F”) Then
Display “Female”
Else
Display “Male”
End If
18
Dual Alternative Decision

Have false leg come out the left
side of the diamond
False
Display “Male"
gender
==
“F"
True
Display “Female"
19
Java if/else Statement

if(boolean expression) { statements to
be executed if true } else { statements
to be executed if false }
String gender;
:
:
if (gender.equals(“f”)) {
System.out.println(“Female”);
}
else{
System.out.println(“Male”);
}
20
Nested IFs



Having a decision structure
inside a decision structure
Allows checking for multiple
conditions
For example, insurance
company assigns risk rating
based on the type of car
21
Nested IFs
If (isCarType = "Sports") Then
If (isCarColor = "Red") Then
insType = "HighRisk"
Else
insType = "Normal"
End If
Else
insType = "Normal"
End If
22
Nested IFs
False
insType="Normal"
True
isCarType
=
"Sports"
False
insType="Normal"
isCarColor
= "Red"
True
insType="HighRisk"
23
Java Nested ifs

Placing an if statement as one of
the statements to be executed in an
if/else clause
if (month == 1) {
System.out.println(“Jan”);}
Nested if
else {if (month == 2) {
System.out.println(“Feb”);}
else { if (month == 3) {
System.out.println(“Mar”);}
else { if (month == 4) {………
24
Case Structure




A large number of nested IFs can
be difficult to understand/debug
The Case structure is an
alternative
Use the keyword Select to
identify the variable to be
checked
Then the keyword Case followed
by the value to check for
25
Case Structure
Select month
Case 1:
Display “Jan”
Case 2:
Display “Feb”
Case 3:
Display “Mar”
Etc. etc.
End Select
26
Case Structure

Can have a default case
 Identifies
what to do if none of the
checked values is true

Appears after all the Case
statements
Select month
Etc. etc.
Case 12:
Display “Dec”
Default:
Display month, “ is not a valid value”
End Select
27
Case Structure
lightColor
“Green”
Display
“Maintain speed"
“Yellow”
Display
“Punch it!"
“Red”
Display
“Stop”
28
SFC Case Structure
29
SFC Case Structure
Click on circle to right of the Case symbol, then Edit, Insert
Specify the value to search for, then click OK
30
SFC Case Structure
Click on True circle and insert statements to perform if true
31
SFC Case Structure
Keep inserting cases until finished
Of course, need to define lightColor and assign a value
32
SFC Case Structure
33
Raptor Case Structure

Doesn’t have one, must use nested IFs
34
Java Case Structure

Uses the keyword switch
 Very
similar to the pseudo code in
SFC


The variable being checked is in
parenthesis
Need break statements in each
case because once the condition
is true, all subsequent statements
are executed
35
Switch

If there were no breaks:
 The
label would be set to Dec
 The “Not a valid month” message would
be displayed
switch (month) {
case 1: monthLabel.setText(“Jan”); break;
case 2: monthLabel.setText(“Feb”); break;
case 3: monthLabel.setText(“Mar”); break;
:
:
:
:
:
default: System.out.println(“Not a valid
month!”);
}
36
Compound Condition



Use AND or OR to connect many
conditions
Each AND & OR links two conditions
AND means both conditions must be
true
 Replaces

nested if
OR means either one or both
conditions must be true
 Replaces
multiple ifs
37
Compound Condition

If (isCarType == "Sports") Then
If (isCarColor == "Red") Then
insType == "HighRisk"
Else
insType == "Normal"
Endif
Else
insType == "Normal"
Endif
If (isCarType == "Sports" AND isCarColor == "Red") Then
insType == "HighRisk"
Else
insType == "Normal"
Endif
38
Compound Condition

If (state == "WA") Then
salesTaxRate = 0
Endif
If (state == "NJ") Then
salesTaxRate = 0
Endif
If (state == "WA" OR state == "NJ") Then
salesTaxRate = 0
Endif
39
Compound Condition

If you specified the following
OR condition
 flavor
== "vanilla" OR flavor ==
"chocolate"


And the ice cream man handed
you a chocolate ice cream cone
Would the ice cream man have
satisfied the condition? YES
40
Compound Condition

If you specified the following
AND condition
 flavor
= ="vanilla" AND flavor ==
"chocolate"


And the ice cream man handed
you a chocolate ice cream cone
Would the ice cream man have
satisfied the condition? NO
41
Truth Table

Shows
2
conditions: x and y
 Every possible combination of T
and F for x and y
 AND and OR compound condition
Boolean value for each combination
Cond x
Cond y
x AND y
x OR y
True
True
True
True
True
False
False
True
False
True
False
True
False
False
False
False
42
Truth Table

Two conditions:
 Cond
x: flavor == “Vanilla”
 Cond
y: coneType == “Sugar”
flavor
coneType
x AND y
x OR y
Vanilla
Sugar
True
True
Vanilla
Waffle
False
True
Chocolate
Sugar
False
True
Chocolate
Waffle
False
False
43
Compound Condition Efficiency


Conditions checked from left to
right
Short circuit evaluation stops
checking in an
 AND
as soon as a false condition is
found
 OR
as soon as a true condition is
found
44
Compound Condition Efficiency

If the programming language
supports short circuit evaluation
 Specify
the conditions so that the
least amount of checks are
performed
 The
fewer the checks, the faster
the program will execute
45
OR Efficiency


Put the condition that is most likely
to be true first in an OR condition
For instance, if 30% of sales come
from NJ and only 5% from WA
If (state == "NJ" OR state == " WA") Then
salesTaxRate = 0
Endif

Means that only 70% of the time is
the 2nd condition checked
would result in 2nd condition
being checked 95% of the time
 Alternative
46
AND Efficiency


Put the condition that is most likely
to be false first in an AND condition
For instance, if 50% of customers
are female and 90% are over 21
If (gender == "F" AND age > 21) Then
Endif

Means that only 50% of the time is
the age checked
 Alternative
would result in gender
being checked 90% of the time
47
Compound Condition Mistakes

Most of the time specifying two
values for the same variable and
connecting them with an AND
 carColor
== "blue" AND carColor
== "red"

Means the condition can never
be true
 How
can the car color be both red
and blue?
48
Compound Condition

However using < or > and an
AND means you can search for
ranges
 salary
< 30000 AND salary >
20000

Means any salary from 20,001 to
29,999 would make the
expression true
49
Compound Condition

In SFC and Raptor use AND and
OR in the diamond shape
50
Java uses && for AND, || for OR
(| is upper case \)
Here's the Java example of the compound AND condition
Prove by changing salary to 44000, compile, and run
51
Condition Mistakes


Be careful with > and <
If we selected students for the
dean's list with the following:
 gpa

> 3.5
It would be incorrect because
 Students
with gpa = 3.5 not
selected

Selection should be
 gpa
>= 3.5
52
Compound Condition Mistakes

Also,
 salary
 No
> 30000 AND salary < 20000
salary value can make this true
 salary
< 30000 OR salary > 20000
 Every

salary value will make this true
Another mistake, not specifying a
full condition
 carColor
= "blue" AND = "red"
 Need
the variable carColor in the
second condition
53
Compound Condition Mistakes

Unnecessary checks
If (salary >= 100000) Then
incomeTaxRate = .28
Else
If (salary < 100000 AND >= 60000) Then
incomeTaxRate = .25
End If
End If

No need to check if < 100000
a second time
54
Combining AND’s and OR’s


The AND is evaluated first (from
left to right) then the OR
So if there were a car with the
following characteristics
 color
= "red", price = 16000, style =
"sports"

And the condition was:
style = "sports" OR color = "red" AND price < 15000

It would be evaluated as follows:
55
Combining AND’s and OR’s
color = "red", price = 16000, style = "sports"
style = “sports” OR color = “red” AND price < 15000
style = “sports” OR True AND price < 15000
style = “sports” OR True AND False
style = “sports” OR False
True OR False
True
56
Combining AND’s and OR’s


AND forms a strong bond between conditions
If there were a file full of cars and we printed
only those cars that satisfied the condition:
style = "sports" OR color = "red" AND price < 15000
Would we get a list of:
Sports cars and cheap red cars
Or:
Cheap sports cars and cheap red cars
57
Combining AND’s and OR’s

AND forms a strong bond between conditions
style = "sports" OR color = "red" AND price < 15000
Means you will get a list of:
Sports cars and cheap red cars
Not:
Cheap sports cars and cheap red cars
style = "sports" OR color = "red" AND price < 15000
58
Combing AND’s and OR’s

To get a list of cheap sports cars and
cheap red cars could specify:
style = "sports" AND price < 15000
OR
color = "red" AND price < 15000

Or (if parentheses are supported)
(style = "sports" OR color = "red") AND price < 15000
59
Combining ANDs and ORs

Three ice cream variables
flavor,

container, topping
Person says give me
Rocky
OR Sprinkles OR Whip Cream

You hand over a
Dish

filled with Sprinkles
Did you satisfy the condition?
Yes
60
Combining ANDs and ORs

Person says give me
Rocky
OR Sprinkles OR Whip Cream

You hand over a
Rocky

Did you satisfy the condition?
No
61
Combining ANDs and ORs

Person says give me
Rocky
OR Sprinkles OR Whip Cream

You hand over a
Rocky
Whip Cream

Did you satisfy the condition?
Yes
62
New Condition Check
Java example of the compound
AND condition and inputting data
63
Run twice and check both true and false legs
64
Conditions



With many conditions, what to
do can get very complicated
Often flowchart or pseudocode
Alternative is a Decision table
Shows
conditions
Every possible combination of
conditional values
For each combination, what the
action(s) should be
65
Decision Table Example
All possible combinations
Conditions
Actions
Temp > 100
F
F
F
F
T
T
T
T
Nausea
F
F
T
T
F
F
T
T
F
T
F
T
F
T
F
T
Go to school
X
X
X
X
X
X
X
X
X
X
Go to doctor
Take aspirin
Take Pepto
X
X
X
X
X
X
X
Stay home
X
Actions to take based on
symptom combinations
66
Java example of the compound
AND condition and GUI
When run, dialog box pops up
Enter data, press OK
Problem: info read from dialog box is text. Have to convert to
numeric with the parseInt function
67
Dialog box disappears and results shown in command prompt
68
Compound Conditions Design Ex

Long distance charge basics:
 Company
charges 10 cents per
minute for all calls outside the
customer’s area code that last over
20 minutes
 All
other calls are 13 cents per
minute

Want to create a program to
calculate the cost of a phone call
69
Exercise

 Accepts
data about one phone call from
user
 Customer
area code (three chars)
 Customer phone number (eight chars)
 Called area code (three chars)
 Called number (eight chars)
 Call time in minutes (four digits)
 Displays:
 All
the inputted data
 Price for the call.
70
Compound Conditions Design Ex

What's the algorithm for this
program?
71
Compound Conditions Design Ex

Long distance charge basics:
 Company
charges 10 cents per
minute for all calls outside the
customer’s area code that last over
20 minutes
 All

other calls are 13 cents per minute
What variables would a program
need to handle this info?
 I.e.
What are the important pieces of
information?
72
Exercise

Create command prompt external
design (XD) of this program

Create a GUI external design (XD)
of this program
73
Exercise

What is the pseudocode so far?
 What
is first command in pseudocode?
 Where
 How
are variables defined?
would you specify the variables?
74
SFC Exercise

So in flow chart what is the first
symbol you enter?
 Rectangle

What is text in rectangle?
75
Exercise

After variables defined what's first
thing that has to happen (ignore the
XD “formatting” for this example)
data in
 What
flow chart symbol?
76
Exercise

Now what do we do?
Can
No,

we calculate price?
have to figure out type of call
What type of symbol is that?
77
Exercise

Now we can calculate price
based on true or false
What
type of symbol is that?
78
Exercise

Now what?
 Show
the results
 What
type of symbol is that?

Full pseudocode
79
Java Exercise

In java, always initialize variables
 Strings
to null
 String
name = null;
 Numbers
 int

to zero
price = 0;
To make a variable value fixed
(unchangeable) define it as final
 final
double TAX_RATE = .065;
80
Java Exercise


In java, must create a lot of stuff
you must import the following
import java.io.*;
import java.util.Scanner;
81
Java Exercise

Then in the main method, create
the following variables and objects
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);


Use the appropriate Scanner .next
function
Must assign read value to a
variable
82
Java Exercise

usually paired with a prompt
:
:
:
:
:
:
qty = keyboard.nextInt();
price = keyboard.nextDouble();
total = price * qty
System.out.println(“The transaction total is ” + total);
:
:
:
:
:
:
83
Java Exercise


Write the java program to
calculate the phone call cost and
implement the command line XD
84
Java Exercise


Modularize the java program to
calculate the phone call cost and
implement the command line XD
85
Comparing Strings


Some languages allow you to use
< and > to compare strings
Since all data stored as numbers
(0’s and 1’s), some letters greater
than others
A
is less than B, B less than C, … Y
is less than Z, Z is less than a, a is
less than b, etc.

Java doesn’t allow <> with strings
86
Boolean Variables




Besides numeric and string
values there are Boolean values
Boolean values are true or false
There are also Boolean variables
that can hold a Boolean value
Can use a Boolean variable in a
expression
87
Boolean Variables
Module main
Declare Integer hoursWorked
Declare Real payRate, salary
Declare Boolean isOvertime
Display “Enter number of hours worked ”
Input hoursWorked
If (hoursWorked > 40) Then
isOvertime = true
Else
isOvertime = false
End If
Display “Enter pay rate ”
Input payRate
If (isOvertime) Then
salary = hoursWorked * (payRate * 1.5)
Else
salary = hoursWorked * payRate
End If
Display “Salary is ”, salary
End Module
88
Points to Remember




Decisions/selections require Boolean
expressions or variables
Boolean expressions result in a value
of true or false
Use relational operator(s) to build
Boolean expression
Can create compound conditions by
combining Boolean expressions with
AND and/or OR operators
89
Assignments

Chap

4 labs 3.1-3.4
Chap
4 lab 3.5
90
```