Date post: | 28-Dec-2015 |
Category: |
Documents |
Upload: | roberta-hampton |
View: | 217 times |
Download: | 1 times |
Intro to Programming & Algorithm Design
Decisions Decisions Decisions
1Copyright 2003 by Janson Industries
This presentation can be viewed on line in a file named: ch04.IntrotoProg.ppt
Assg
Copyright 2014 by Janson Industries
Objectives Explain
Boolean expressions
Comparison operators
IF/THEN/ELSE logic
AND and OR logic
Nested IFs
Case structure
2
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
Boolean Expression In addition you can combine
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
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
Boolean Expression Negative logic can be confusing
Try not to use
For instance, instead of if (!(salary > 75000))
Use if (salary <= 75000)
Often, in programming languages, the Boolean expression is enclosed in ()
9
Copyright 2014 by Janson Industries
Boolean Expression However sometimes the non-
negative 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
Copyright 2014 by Janson Industries
Boolean Expression Can perform same selection
with different operators
11
If (price > limit) Then finalCost = price * luxuryTax Else
finalCost = price * salesTax Endif
If (price <= limit) Then finalCost = price * salesTax Else
finalCost = price * luxuryTax Endif
Copyright 2014 by Janson Industries
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 to know business/data
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
Copyright 2014 by Janson Industries
Boolean Expression Gotcha Must compare values of the same type
Bad expressions: totalCost == "Joe Smith"
TotalCost is a numeric variable
gender > 10 Gender is a string variable
10 == "A" Comparing a number to a string
13
Copyright 2014 by Janson Industries
Decision Structure In pseudocode, use the word If followed by
a Boolean condition in parenthesis
Statements to be executed if true follow Then and are indented
14
If (month == 1) Then
Display “Jan”
End If
If (month == 2) Then
Display “Feb”
End If
Copyright 2014 by Janson Industries
Boolean Expression In flow charts, put into diamond
symbol (selection)
Two logic paths out of diamond True
False
15
month== 1
Display “Jan”
True
False
month== 2
Display “Feb”
True
False
Copyright 2014 by Janson Industries
Java if Statement
16
if (month == 1) {System.out.println(“Jan”);
}if (month == 2) {
System.out.println(“Feb”);}
Syntax of an if/else statement if(boolean expression) { statements to be executed if true }
Copyright 2014 by Janson Industries
Java if Statement
17
String gender; : :if (gender.equals(“f”)) {
System.out.println(“Female”);}if (gender.equals(“m”)) {
System.out.println(“Male”);}
When comparing a String variable must use .equals
Copyright 2014 by Janson Industries
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
18
If (gender == “F”) Then
Display “Female”
Else
Display “Male”
End If
Copyright 2014 by Janson Industries
Dual Alternative Decision Have false leg come out the left
side of the diamond
19
gender == “F"
TrueFalse
Display “Male" Display “Female"
Copyright 2014 by Janson Industries
Java if/else Statement
20
String gender; : :if (gender.equals(“f”)) {
System.out.println(“Female”);}else{
System.out.println(“Male”);}
if(boolean expression) { statements to be executed if true } else { statements to be executed if false }
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
Nested IFs
22
If (isCarType = "Sports") Then
If (isCarColor = "Red") Then
insType = "HighRisk"
Else
insType = "Normal"
End If
Else
insType = "Normal"
End If
Copyright 2014 by Janson Industries
Nested IFs
23
isCarType =
"Sports"
TrueFalse
isCarColor = "Red"
insType="HighRisk"
TrueinsType="Normal" False
insType="Normal"
Copyright 2014 by Janson Industries
Java Nested ifs
24
if (month == 1) { System.out.println(“Jan”);}
else {if (month == 2) { System.out.println(“Feb”);}
else { if (month == 3) { System.out.println(“Mar”);}
else { if (month == 4) {………
Nested if
Placing an if statement as one of the statements to be executed in an if/else clause
Copyright 2014 by Janson Industries
Case Structure
25
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
Copyright 2014 by Janson Industries
Case Structure
26
Select month
Case 1:
Display “Jan”
Case 2:
Display “Feb”
Case 3:
Display “Mar”
Etc. etc.
End Select
Copyright 2014 by Janson Industries
Case Structure
27
Can have a default case Identifies what to do if none of the checked values is true
Appears after all the Case statements
Select monthEtc. etc.Case 12:
Display “Dec”Default:
Display month, “ is not a valid value”End Select
Copyright 2014 by Janson Industries
Case Structure
28
lightColor
“Green”
Display “Stop”
Display “Maintain speed"
“Red”
Display “Punch it!"
“Yellow”
Copyright 2014 by Janson Industries
SFC Case Structure
30
Click on circle to right of the Case symbol, then Edit, Insert
Specify the value to search for, then click OK
Copyright 2014 by Janson Industries
SFC Case Structure
31
Click on True circle and insert statements to perform if true
Copyright 2014 by Janson Industries
SFC Case Structure
32
Keep inserting cases until finished Of course, need to define lightColor and assign a value
Copyright 2014 by Janson Industries
Java Case Structure
35
Uses the keyword switch Very similar to the pseudo code in SFC
The value being checked is in parenthesis
Need break statements in each case because once the condition is true, all subsequent statements are executed
Copyright 2014 by Janson Industries36
Switch
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!”);
}
If there were no breaks: The label would be set to Dec The “Not a valid month” message would be displayed
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
Compound Condition So instead of nested if:
38
If (isCarType == "Sports") Then If (isCarColor == "Red") Then insType == "HighRisk" Else insType == "Normal" EndifElse insType == "Normal"Endif
If (isCarType == "Sports" AND isCarColor == "Red") Then insType == "HighRisk"
Else insType == "Normal"
Endif
Copyright 2014 by Janson Industries
Compound Condition So instead of multiple ifs:
39
If (state == "WA") Then salesTaxRate = 0 EndifIf (state == "NJ") Then salesTaxRate = 0 Endif
If (state == "WA" OR state == "NJ") Then salesTaxRate = 0 Endif
Copyright 2014 by Janson Industries
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?
40
YES
Copyright 2014 by Janson Industries
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?
41
NO
Copyright 2014 by Janson Industries
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
42
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
Copyright 2014 by Janson Industries
Truth Table Two conditions:
Cond x: flavor == “Vanilla”
Cond y: coneType == “Sugar”
43
flavor coneType x AND y x OR y
Vanilla Sugar True True
Vanilla Waffle False True
Chocolate Sugar False True
Chocolate Waffle False False
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
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
Means that only 70% of the time is the 2nd condition checked Alternative would result in 2nd condition
being checked 95% of the time 46
If (state == "NJ" OR state == " WA") Then salesTaxRate = 0 Endif
Copyright 2014 by Janson Industries
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
Means that only 50% of the time is the age checked Alternative would result in gender
being checked 90% of the time 47
If (gender == "F" AND age > 21) Then admissionType = "Free" Endif
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
Compound Condition In SFC and Raptor use AND and
OR in the diamond shape
50
Copyright 2014 by Janson Industries51
Here's the Java example of the compound AND condition
Java uses && for AND, || for OR (| is upper case \)
Prove by changing salary to 44000, compile, and run
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
Compound Condition Mistakes Also,
salary > 30000 AND salary < 20000 No 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
Copyright 2014 by Janson Industries
Compound Condition Mistakes Unnecessary checks
No need to check if < 100000 a second time
54
If (salary >= 100000) Then
incomeTaxRate = .28
Else
If (salary < 100000 AND >= 60000) Then
incomeTaxRate = .25
End If
End If
Copyright 2014 by Janson Industries
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:
It would be evaluated as follows:
55
style = "sports" OR color = "red" AND price < 15000
Copyright 2014 by Janson Industries
Combining AND’s and OR’s
56
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
Copyright 2014 by Janson Industries
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:
57
style = "sports" OR color = "red" AND price < 15000
Would we get a list of:
Sports cars and cheap red carsOr:
Cheap sports cars and cheap red cars
Copyright 2014 by Janson Industries
Combining AND’s and OR’s AND forms a strong bond between conditions
58
style = "sports" OR color = "red" AND price < 15000
Means you will get a list of:
Sports cars and cheap red carsNot:
Cheap sports cars and cheap red cars
color = "red" AND price < 15000style = "sports" OR
Copyright 2014 by Janson Industries
To get a list of cheap sports cars and cheap red cars could specify:
Or (if parentheses are supported)
Combing AND’s and OR’s
59
style = "sports" AND price < 15000
color = "red" AND price < 15000
OR
(style = "sports" OR color = "red") AND price < 15000
Copyright 2014 by Janson Industries
Combining ANDs and ORs Three ice cream variables
flavor, container, topping
Person says give me Rocky Road AND Sugar Cone
OR Sprinkles OR Whip Cream
You hand over a Dish filled with Sprinkles
Did you satisfy the condition?60Yes
Copyright 2014 by Janson Industries
Combining ANDs and ORs Person says give me
Rocky Road AND Sugar Cone OR Sprinkles OR Whip Cream
You hand over a Rocky Road in a Dish
Did you satisfy the condition?
61
No
Copyright 2014 by Janson Industries
Combining ANDs and ORs Person says give me
Rocky Road AND Sugar Cone OR Sprinkles OR Whip Cream
You hand over a Rocky Road in a Dish with
Whip Cream
Did you satisfy the condition?
62
Yes
Copyright 2014 by Janson Industries
New Condition Check
63
Java example of the compound AND condition and inputting
data
Copyright 2014 by Janson Industries
Conditions With many conditions, what to do
can get very complicated
Often flowchart or pseudocode hard to read
Alternative is a Decision table Shows conditions Every possible combination of
conditional values For each combination, what the
action(s) should be
65
Copyright 2014 by Janson Industries67
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
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
Exercise Further info about program:
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
Copyright 2014 by Janson Industries
Compound Conditions Design Ex
What's the algorithm for this program?
71
Algorithm Answer
Copyright 2014 by Janson Industries
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?
72Answer 2
Copyright 2014 by Janson Industries
Exercise
Create command prompt external design (XD) of this program
Answer 2.5
Create a GUI external design (XD) of this program
Answer 2.6
73
Copyright 2014 by Janson Industries
Exercise What is the pseudocode so far?
What is first command in pseudocode?
Where are variables defined?
How would you specify the variables?
74
Answer 3
Copyright 2014 by Janson Industries
SFC Exercise So in flow chart what is the first
symbol you enter?
Rectangle
What is text in rectangle?
75
Answer 4
Copyright 2014 by Janson Industries
Exercise After variables defined what's first
thing that has to happen (ignore the XD “formatting” for this example)
Read data in
What flow chart symbol?
76
Answer 5
Copyright 2014 by Janson Industries
Exercise Now what do we do?
Can we calculate price?
No have to figure type of call it is
What type of symbol is that?
77
Answer 6
Copyright 2014 by Janson Industries
Exercise
Now we can calculate price based on true or false
What type of symbol is that?
78
Answer 7
Copyright 2014 by Janson Industries
Exercise Now what?
Show the results
What type of symbol is that?
79
Answer 8
Copyright 2014 by Janson Industries
Exercise Pseudocode
80
Module mainDeclare String custAreaCode, custPhoneNum,
calledAreaCode, calledPhoneNumDeclare Integer minutesDeclare Real priceDeclare Real LOW_RATE = 0.10Declare Real HIGH_RATE = 0.13Declare Integer TIME_LIMIT = 20Input custAreaCode, custPhoneNum,
calledAreaCode, calledPhoneNum, minutesIf custAreaCode != calledAreaCode AND
minutes > TIME_LIMIT Thenprice = minutes * LOW_RATE
Elseprice = minutes * HIGH_RATE
End IfDisplay custAreaCode, custPhoneNum,
calledAreaCode, calledPhoneNum, priceEnd Module
Copyright 2014 by Janson Industries
Java Exercise
81
In java, always initialize variables
Strings to null String name = null;
Numbers to zero int price = 0;
To make a variable value fixed (unchangeable) define it as final
final double TAX_RATE = .065;
Copyright 2014 by Janson Industries82
Java Exercise In java, must create a lot of stuff to read from command line
First, before the class header, you must import the following
import java.io.*;import java.util.Scanner;
public class ClassHeader {
Copyright 2014 by Janson Industries83
Java Exercise Then in the main method, create the following variables and objects
Use the appropriate Scanner .next function Must assign read value to a variable
public static void main(String[] args) {Scanner keyboard = new Scanner(System.in);int numRead = 0;
numRead = keyboard.nextInt();
Copyright 2014 by Janson Industries84
Java Exercise Reads (.next(), nextInt(), etc.) usually
paired with a prompt
: : : : : :System.out.println(“Please enter qty of purchase”);qty = keyboard.nextInt();System.out.println(“Please enter item price”);price = keyboard.nextDouble();total = price * qtySystem.out.println(“The transaction total is ” + total);
: : : : : :
Copyright 2014 by Janson Industries
Java Exercise
85
Write the java program to calculate the phone call cost and implement the command line XD
Answer 9
Copyright 2014 by Janson Industries
Java Exercise
86
Modularize the java program to calculate the phone call cost and implement the command line XD
Answer 10
Copyright 2014 by Janson Industries
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 strings87
Copyright 2014 by Janson Industries
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 condition instead of a Boolean expression
88
Copyright 2014 by Janson Industries
Boolean Variables
89
Module mainDeclare Integer hoursWorkedDeclare Real payRate, salaryDeclare Boolean isOvertimeDisplay “Enter number of hours worked ”Input hoursWorkedIf (hoursWorked > 40) Then
isOvertime = trueElse
isOvertime = falseEnd IfDisplay “Enter pay rate ”Input payRateIf (isOvertime) Then
salary = hoursWorked * (payRate * 1.5)
Elsesalary = hoursWorked * payRate
End IfDisplay “Salary is ”, salary
End Module
Copyright 2014 by Janson Industries
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
90