Lecture 10: Control Flow. Selection (Decision) structures.
-
Upload
ross-robbins -
Category
Documents
-
view
226 -
download
3
Transcript of Lecture 10: Control Flow. Selection (Decision) structures.
Lecture 10: Control Flow. Selection (Decision) structures
2
Lecture Contents:
Quiz on C++ Functions The if statement (“then” version) The if statement (“then – else” version) Nested if...else statements versus
sequence of if statements Demo programs Exercises
3
Quiz #2on
C++ Functions
44.
Control Structures
Three methods of processing a program– In sequence– Branching– Looping
Branch: altering the flow of program execution by making a selection or choice
Loop: altering the flow of program execution by repetition of statement(s)
55.
Flow of Execution
6
The if statement (“then” version)
Syntax and flowchart fragment:
if (<expression>) <statement>;
7
The if statement (“then” – else version)
Syntax and flowchart fragment:
if (<expression>) <statement_1>;
else <statement_2>;
8
Nested if…else statements vs. sequence of if statements
Nested if … else … statements. Example: ambiguity with two ifs and one else clause// increment n_pos, n_zero, n_neg// depending on the value of x if (x > 0) n_pos = n_pos + 1; if (x < 0) n_neg = n_neg + 1; else n_zero = n_zero + 1; The rule: An else is matched with the last if that
doesn’t have its own else.
9
Nested if…else statements vs. sequence of if statements
Nested if … else … statements. The rule: An else is matched with the last if that doesn’t have its own else.
Example:// increment n_pos, n_zero, n_neg// depending on the value of xif (x > 0)n_pos = n_pos + 1;else if (x < 0) n_neg = n_neg + 1;
else n_zero = n_zero + 1;
10
Nested if…else statements vs. sequence of if statements
Sequence of if statements Example:// increment n_pos, n_zero, n_neg// depending on the value of xif ( x > 0 ) n_pos = n_pos + 1;if ( x < 0 ) n_neg = n_neg + 1;if ( x == 0 ) n_zero = n_zero + 1;// less efficient version because all// three conditions are always tested
11
Else If clauseA variation of the IF…”THEN”…ELSE statement uses several conditions with ELSE and IF keywords:
if (condition1) action1 else if (condition2) action2 else if (condition3) action3 else action4
Any number of ELSE IF clauses is permitted.• The conditions are evaluated from the top, and if one of them is True, the
corresponding block of statements (action I ) is executed.• The ELSE clause will be executed if none of the previous expressions is True.• Example comes on next slide.
12
Else If clause
cout << “\nEnter score:”; cin >> score;
if (score < 60) Result = “Fail”; else if (score < 75) Result = “Pass”; else if (score < 90) Result = “Very good”; else
Result = “Excellent”;
13
Else If clause
The order of comparisons is vital in an IF…THEN…ELSE IF… statements. Try to switch the first two conditions of the last page code and you may get quite unexpected results
if (score < 75) Result = “Pass”; else if (score < 60) Result = “Fail”; else if (score < 90) Result = “Very good”; else Result = “Excellent”; Let’s assume score is 48. The first condition checked (48<75) will return True and
it will assign “Pass” to Result, and then it will skip the other remaining clauses.ERROR in the algorithm implemented! A student can’t pass a test with grade < 60.MORAL: Be careful and test your code if it uses ELSE IF clauses.
14
Muiltiple IF…THEN… structures versus Else If clause
After True condition is found, C++ executes the associated stmts and skips the remaining clauses. It continues program execution with stmt immediately after last ELSE clause. All following ELSE IF clauses are skipped, and the code runs a bit faster. That’s why the complicated ELSE IF structure should be preferred to the equivalent series of simple IF… statements shown below:
if (score < 60) Result = “Fail”; if (score < 75) Result = “Pass”; if (score < 90) Result = “Very good”; if (score >=90) Result = “Excellent”;
C++ will evaluate the conditions of all the IF stmts, even if the score is less than 50.
15
More on if statement(s)
Extract from Friedman/Koffman, chapter 4
Selection Structures: if and switch Statements
Chapter 4
17
Selection Statements
– In this chapter we study statements that allow alternatives to straight sequential processing. In particular:• if statements (do this only if a condition is true)• if-else statements (do either this or that)• Logical expressions (evaluate to true or false)• Boolean operators (not: ! and: && or: ||)
18
4.1 Control Structures
– Programs must often anticipate a variety of situations.
– Consider an Automated Teller Machine:• ATMs must serve valid bank customers. They must
also reject invalid PINs.
• The code that controls an ATM must permit these different requests.
• Software developers must implement code that anticipates all possible transactions.
19
4.2 Logical Expressions
Declarationint month = 9;Expression is(month > 9) False
(month < 9) False
(month >= 9) True
(month <= 9) True
20
Boolean Variables
bool variable Included with C++ compiler
bool leapYear;
leapYear = true; // Non zero return value
leapYear = false; // Zero return value
21
Boolean Expressions
Examples (Write T for True, or F for False): int n1 = 55;
int n2 = 75;
n1 < n2 // _____
n1 > n2 // _____
(n1 + 35) > n2 // _____
(n1-n2) < 0.1 // _____
n1 == n2 // _____
22
Logical Expressions
– Logical expressions often use these relational operators:
> Greater than< Less than>= Greater than or equal<= Less than or equal== Equal!= Not equal
23
Logical Operators
Logical operator (&& means AND) used in an if...else statement:
( (tryIt >= 50) && (tryIt <= 1500) )
Logical operator (| | means OR) used in an if...else statement:
( (tryIt < 50) | | (tryIt > 1500) )
24
Using &&
Assume tryIt = 90, Is tryIt within the range of 50 and 1500 ?
( (tryIt >= 50) && (tryIt <= 1500) )
( ( 90 >= 50) && ( 90 <= 1500) )
( 1 && 1 )
1
25
Using ||
Assume tryIt = 99 Is tryIt outside the range of 50 and 1500 ?
( (tryIt < 50) || (tryIt > 1500) )
( ( 99 < 50) || ( 99 > 1500) )
( 0 || 0 )
0
26
Truth Tables for Boolean Operators
Truth tables for Logical operators !, ¦¦, &&– ! means unary NOT /negation/ operator– && means binary AND /conjunction/ operator– ¦¦ means binary OR /disjunction/operator– 1 is a symbol for true, 0 is a symbol for false
Operation Result Operation Result Operation Result! 0! 1
10
1 ¦¦ 11 ¦¦ 00 ¦¦ 10 ¦¦ 0
1110
1 && 11 && 00 && 10 && 0
1000
27
Truth Tables for Boolean Operators or Logical Functions
Boolean operators = Logical functions Arguments are logical/boolean values –
false/true or 0/1 Unary logical NOT function, denoted !
Arg Function0 1 !0 = 11 0 !1 = 0
28
Truth Tables for Boolean Operators or Logical Functions
Boolean operators = Logical functions Arguments are logical/boolean values –false/true or 0/1 Binary logical AND function, denoted &&, a && b
Arg1 Arg2 Function 0 0 0 0 && 0 = 0 0 1 0 0 && 1 = 0 1 0 0 1 && 0 = 0 1 1 1 1 && 1 = 1
29
Truth Tables for Boolean Operators or Logical Functions
Boolean operators = Logical functions Arguments are logical/boolean values –false/true or 0/1 Binary logical OR function, denoted ||, a || b
Arg1 Arg2 Function 0 0 0 0 || 0 = 0 0 1 1 0 || 1 = 1 1 0 1 1 || 0 = 1 1 1 1 1 || 1 = 1
30
Truth Tables for Boolean Operators or Logical Functions
Boolean operators = Logical functions Arguments are logical/boolean values –false/true or 0/1
Binary logical EOR function, denoted , a bArg1 Arg2 Function 0 0 0 0 0 = 0 0 1 1 0 1 = 1 1 0 1 1 0 = 1 1 1 0 1 1 = 0
31
Bit-wise logical operators
& - bit wise AND operator | - bit wise OR operator
32
De Morgan laws
In logic, De Morgan's laws (or De Morgan's theorem) are rules in formal logic relating pairs of dual logical operators in a systematic manner expressed in terms of negation. The relationship so induced is called De Morgan duality.
Augustus De Morgan originally observed that in classical propositional logic the following relationships hold:
not (P and Q) = (not P) or (not Q) not (P or Q) = (not P) and (not Q)
33
Boolean Algebra
Full set of boolean binary functionsArgs Functions a ea b n o o d r r0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 10 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 11 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 11 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
34
Boolean Algebra
Minimal /basic/ set of boolean functions
– Negation or logical not
not a !a
– Conjunction or logical multiplication
a and b a && b
– Disjunction or logical addition
a or b a || b
35
Boolean Algebra
Exclusive OR formulated through basic functions
a b = (not a and b) or (a and not b)
a b = (!a && b) || (a && !b)
36
Precedence of Operators
Precedence: most operators are evaluated (grouped) in a left-to-right order:– a / b / c / d is equivalent to
(((a/b)/c)/d) Assignment operators group in a right-to-
left order so the expression – x = y = z = 0.0 is equivalent to
(x=(y=(z=0.0)))
37
Operator Description Grouping Highest ::
() Scope resolution Function call
Left to right
Unary !, +, - Not, unary plus/minus Right to left
Multiplicative * / % Multipy/divide/remainder Left to right
Additive + - Binary plus, minus Left to right
Input/Output >> << Extraction / insertion Left to right
Relational < > <= >=
Less/Greater than Less/Greater or equal
Left to right
Equality == != Equal, Not equal Left to right
and && Logical and Left to right
or ¦¦ Logical or Left to right
Assignment = Assign expression Right to left
Precedence of Operators
38
Boolean Assignment
bool same;
same = true;
Form: variable = expression;
Example: same = (x = = y);
39
4.3 Introduction to the if Dependent Control Statement
– The if is the first statement that alters strict sequential control.
– General form
if ( logical-expression ) true-part ;
• logical-expression: any expression that evaluates to nonzero (true) or zero (false).
• In C++, almost everything is true or false.
40
if Control Statementswith Two Alternatives
– The logical expression is evaluated. When true, the true-part is executed and the false-part is disregarded. When the logical expression is false, the false-part executes.
– General Form
if ( logical-expression ) true-part ;else false-part ;
41
What happens when an if statement executes?
• After the logical expression of the if statement evaluates, the true-part executes only if the logical expression was true.
gross >100.0
False
net=gross-tax net=gross True
42
Programming Tip
Using = for == is a common mistake. For example the following statements are legal:
int x = 25;
Because assignment statements evaluate to the
expression on the right of =, x = 1 is always
1, which is nonzero, which is true:
if (x = 1) // should be (x == 1)
43
4.4 if Statements with Compound Alternatives
– General form (also known as a block): {
statement-1 ; statement-2 ;
...statement-N ;
} – The compound statement groups together many
statements that are treated as one.
44
Writing Compound Statements
if (transactionType == 'c'){ // process check cout << "Check for $" << transactionAmount << endl; balance = balance - transactionAmount;}else{ // process deposit cout << "Deposit of $" << transactionAmount << endl; balance = balance + transactionAmount;}
45
4.6 Checking the Correctness of an Algorithm
Verifying the correctness of an algorithm is a critical step in algorithm design and often saves hours of coding and testing time.
We will now trace the execution of the refined algorithm for the payroll problem solved in the last section.
46
4.7 Nested if Statements and Multiple Alternative Decisions
– Nested logic is one control structure containing another similar control structure.
– An if...else inside another if...else. e.g. (the 2nd if is placed on the same line as the 1st):
47
Example of nested logic
if(x > 0)
numPos = numPos + 1;
else
if(x < 0)
numNeg = NumNeg + 1;
else
numZero = numZero + 1;
48
Example of nested logic
X numPos numNeg numZero
3.0 _______ _______ _______
-3.6 _______ _______ _______
4.0 _______ _______ _______
Assume all variables initialized to 0
49
Writing a Nested if as a Multiple-Alternative Decision
Nested if statements can become quite complex. If there are more than three alternatives and indentation is not consistent, it may be difficult to determine the logical structure of the if statement.
50
Function displayGrade
void displayGrade ( int score)
{
if (score >= 90) cout << "Grade is A " << endl;
else if (score >= 80) cout << "Grade is B " << endl;
else if (score >= 70) cout << "Grade is C " << endl;
else if (score >= 60) cout << "Grade is D " << endl;
else cout << "Grade is F " << endl;
}
51
Order of Conditions
if (score >= 60)
cout << "Grade is D " << endl;
else if (score >= 70)
cout << "Grade is C " << endl;
else if (score >= 80)
cout << "Grade is B " << endl;
else if (score >= 90)
cout << "Grade is A " << endl;
else
cout << "Grade is F " << endl;
52
Short Circuit Evaluation
(single == ‘y’ && gender == ‘m’ && age >= 18) – If single is false, gender and age aren’t evaluated
(single == ‘y’ || gender == ‘m’ || age >= 18)– If single is true, gender and age are not evaluated
53
4.9 Common Programming Errors
Failing to use { and } if(Grade >= 3.5)
// The true-part is the first cout only
cout <<"You receive an A !!!";
cout <<"You made it by " << (Grade-3.5) << " points";
else <<<< Error >>>>
54
Common Programming Errors
There are no compile time errors next, but there is an intent error.
else cout << "Sorry, you missed an A. "; cout << "You missed it by " << 3.5-Grade << " points"; With the above false part, you could get this
confusing output (when Grade = 3.9): You received an A !!!. You made it by 0.4 points.You missed it by -0.4 points
55
Corrected Version:
if(Grade >= 3.5){ cout << "You received an A !!! " << endl; cout << "You made it by " << (Grade-3.5) << " points"; // Do other things if desired}else { cout << " You did NOT receive an A !!! "; cout << "You missed it by " << (3.5-Grade) <<" points";}
56
Exercise 10.1
Build programs based on branch algorithms:
To add, subtract, multiply, and divide two
integer values checking the valid divisor (!=0) condition
57
Exercise 10.2
Build programs based on branch algorithms: To associate noise loudness with the effect of noise
using a table data:
Loudness in decibels(db) Perception
50 or lower quiet
51-90 annoying
91-110 very annoying
Above 110 uncomfortable
58
Exercise 10.3
Build programs based on branch algorithms:
To implement nested if statements using sample flow chart algorithms
59
Exercise 10.4
Build programs based on branch algorithms:
To compute area of a triangle by Heron’s formulae
60
Exercise 10.5
Build programs based on branch algorithms:
To test an integer value as a valid leap year (divisible by 4 but not by 100, except that years divisible by 400)
61
Exercise 10.6
Build programs based on branch algorithms:
To find roots (solutions) of a linear equation bx + c = 0
62
Exercise 10.7
Build programs based on branch algorithms:
To find roots (solutions) of a quadratic equation ax2 + bx + c = 0
63
Before lecture end
Lecture:
Control Flow. Selection (decision) structures
More to read:
Friedman/Koffman, Chapter 04
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 4: Selection Structures: if and switch Statements
Problem Solving,
Abstraction, and Design using C++ 5e
by Frank L. Friedman and Elliot B. Koffman
65Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Objectives
• Become familiar with selection statements
• Compare numbers, characters, and strings
• Use relational, equality, and logical operators
• Write selection statements with one or two alternatives
• Select among multiple choices
66Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
4.1 Control Structures
• Regulate the flow of execution
• Combine individual instructions into a single logical unit with one entry point and one exit point.
• Three types: sequential, selection, repetition
67Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Sequential Execution
• Each statement is executed in sequence.
• A compound statement is used to specify sequential control:{
statement1;statement2;
.
.
.
statementn;}
68Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
4.2 Logical Expressions
• C++ control structure for selection is the if statement.
• E.g.:if (weight > 100.00)
shipCost = 10.00;
else
shipCost = 5.00;
69Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Relational and Equality Operators
• Logical expressions (conditions) are used to perform tests for selecting among alternative statements to execute.
• Typical forms:variable relational-operator variable
variable relational-operator constant
variable equality-operator variable
variable equality-operator constant
• Evaluate to Boolean (bool) value of true or false
70Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Table 4.1 Rational and Equality Operators
71Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example
x
x <= 0
-5
-5
true
72Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example
x y
x >= y
-5
-5
false
7
7
73Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Logical Operators
• && (and)
• || (or)
• ! (not)
• Used to form more complex conditions, e.g.(salary < minSalary) || (dependents > 5)
(temperature > 90.0) && (humidity > 0.90)
winningRecord && (!probation)
74Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Table 4.3 && Operator
75Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Table 4.4 || Operator
76Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Table 4.5 ! Operator
77Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Table 4.6 Operator Precedence
78Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example
flagx y z
3.0 4.0 2.0 false
x + y / z <= 3.5
2.0
5.0
false
79Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example
flagx y z
3.0 4.0 2.0 false
! flag || (y + z >= x - z)
6.0 1.0
true
true
true
80Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Table 4.7 English Conditions as C++ Expressions
81Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Comparing Characters and Strings
• Letters are in typical alphabetical order
• Upper and lower case significant
• Digit characters are also ordered as expected
• String objects require string library– Compares corresponding pairs of characters
82Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Table 4.8 Examples of Comparisons
83Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Boolean Assignment
• Assignment statements have general form
variable = expression;
• E.g.: (for variable called same of type bool)
same = true;
same = (x == y);
84Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Additional Examples
• inRange = (n > -10) && (n < 10);
• isLetter = ((‘A’ <= ch) && (ch <= ‘Z’)) ||
((‘a’ <= ch) && (ch <= ‘z’));
• even = (n % 2 == 0);
85Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Writing bool Values
• Boolean values are represented by integer values in C++– 0 for false– non-zero (typically 1) for true
• Outputting (or inputting) bool type values is done with integers
86Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
4.3 The if Control Structure
• Allows a question to be asked, e.g. “is x an even number.”
• Two basic forms– a choice between two alternatives– a dependent (conditional) statement
87Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
if Statement with Two Alternatives
• Form: if (condition)
statementT
else
statementF
• E.g.: if (gross > 100.00) net = gross - tax;else net = gross;
88Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Figure 4.4 Flowchart of if statement with two alternatives
89Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
if Statement with Dependent Statement
• When condition evaluates to true, the statement is executed; when false, it is skipped
• Form: if (condition)
statementT
• E.g.: if (x != 0) product = product * x;
90Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Figure 4.5 Flowchart of if statement with a dependent
91Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
4.4 if Statements with Compound Alternatives
• Uses { } to group multiple statements
• Any statement type (e.g. assignment, function call, if) can be placed within { }
• Entire group of statements within { } are either all executed or all skipped when part of an if statement
92Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example 4.11
if (popToday > popYesterday)
{
growth = popToday - popYesterday;
growthPct = 100.0 * growth / popYesterday;
cout << “The growth percentage is “ << growthPct;
}
93Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example 4.11 (continued)
if (transactionType == ‘c’)
{ // process check
cout << “Check for $” << transactionAmount << endl;
balance = balance - transactionAmount;
}
else
{ // process deposit
cout << “Deposit of $” << transactionAmount << endl;
balance = balance + transactionAmount;
}
94Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Program Style
• Placement of { } is a stylistic preference
• Note placement of braces in previous examples, and the use of spaces to indent the statements grouped by each pair of braces.
95Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Tracing an if Statement
• Hand tracing (desk checking) is a careful step-by-step simulation on paper of how the computer would execute a program’s code.
• Critical step in program design process
• Attempts to verify that the algorithm is correct
• Effect shows results of executing code using data that are relatively easy to process by hand
96Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Table 4.9 Step-by-Step Hand Trace of if statement
97Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Decision Steps in Algorithms
• Algorithm steps that select from a choice of actions are called decision steps
• Typically coded as if statements
98Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: Statement
Your company pays its hourly workers once a week. An employee’s pay is based upon the number of hours worked (to the nearest half hour) and the employee’s hourly pay rate. Weekly hours exceeding 40 are paid at a rate of time and a half. Employees who earn over $100 a week must pay union dues of $15 per week. Write a payroll program that will determine the gross pay and net pay for an employee.
99Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: Analysis
The problem data include the input data for hours worked and hourly pay and two required outputs, gross pay and net pay. There are also several constants: the union dues ($15), the minimum weekly earnings before dues must be paid ($100), the maximum hours before overtime must be paid (40), and the overtime rate (1.5 times the usual hourly rate). With this information, we can begin to write the data requirements for this problem. We can model all data using the money (see Section 3.7) and float data types.
100Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: Data Requirements
• Problem ConstantsMAX_NO_DUES = 100.00
DUES = 15.00
MAX_NO_OVERTIME = 40.0
OVERTIME_RATE = 1.5
101Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: Data Requirements
• Problem Inputfloat hours
float rate
• Problem Outputfloat gross
float net
102Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: Program Design
The problem solution requires that the program read the hours worked and the hourly rate before performing any computations. After reading these data, we need to compute and then display the gross pay and net pay. The structure chart for this problem (Figure 4.6) shows the decomposition of the original problem into five subproblems. We will write three of the subproblems as functions. For these three subproblems, the corresponding function name appears under its box in the structure chart.
103Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Figure 4.6 Structure chart for payroll problem
104Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: Initial Algorithm
1.Display user instructions (function instructUser).
2.Enter hours worked and hourly rate.3.Compute gross pay (function computeGross).4.Compute net pay (function computeNet).5.Display gross pay and net pay.
105Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: instructUser Function
• Global constants - declared before function main
MAX_NO_DUES
DUES
MAX_NO_OVERTIME
OVERTIME_RATE
106Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: instructUser Function
• Interface– Input Arguments
• none
– Function Return Value• none
– Description• Displays a short list of instructions and information
about the program for the user.
107Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: computeGross Function
• Interface– Input Arguments
• float hours
• float rate
– Function Return Value• float gross
108Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: computeGross Function
• FormulaGross pay = Hours worked Hourly pay
• Local Datafloat gross
float regularPay
float overtimePay
109Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: computeGross Function - Algorithm
3.1 If the hours worked exceeds 40.0 (max
hours before overtime)
3.1.1 Compute regularPay
3.1.2 Compute overtimePay
3.1.3 Add regularPay to overtimePay
to get gross
Else
3.1.4 Compute gross as house * rate
110Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: computeNet Function
• Interface– Input Arguments
• float gross
– Function Return Value• float net
• Formulanet pay = gross pay - deductions
• Local Datafloat net
111Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Case Study: computeNet Function - Algorithm
4.1 If the gross pay is larger than $100.00
4.1.1 Deduct the dues of $15 from gross
pay
Else
4.1.2 Deduct no dues
112Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Listing 4.1 Payroll problem with functions
113Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Listing 4.1 Payroll problem with functions (continued)
114Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Listing 4.1 Payroll problem with functions (continued)
115Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Listing 4.1 Payroll problem with functions (continued)
116Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Listing 4.1 Payroll problem with functions (continued)
117Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Listing 4.2 Sample run of payroll program with functions
118Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Global Constants
• Enhance readability and maintenance– code is easier to read– constant values are easier to change
• Global scope means that all functions can reference
119Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Identifier Scope
• Variable gross in main function
• Local variable gross in function computeGross.
• No direct connection between these variables.
120Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Data Flow Information and Structure Charts
• Shows which identifiers (variables or constants) are used by each step
• If a step gives a new value to a variable, it is consider an output of the step.
• If a step uses the value of an variable without changing it, the variable is an input of the step.
• Constants are always inputs to a step.
121Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Software Development Method
1. Analyze the problem statement
2. Identify relevant problem data
3. Use top-down design to develop the solution
4. Refine subproblems starting with an analysis similar to step 1
122Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
4.6 Checking Algorithm Correctness
• Verifying the correctness of an algorithm is a critical step in algorithm design and often saves hours of coding and testing time
123Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example - Trace of Payroll Problem
1. Display user instructions.
2. Enter hours worked and hourly rate.
3. Compute gross pay.
3.1. If the hours worked exceed 40.0 (max hours before overtime)
3.1.1. Compute regularPay.
3.1.2. Compute overtimePay.
3.1.3. Add regularPay to overtimePay to get gross.
else
3.1.4. Compute gross as hours * rate.
124Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example - Trace of Payroll Problem
4. Compute net pay.
4.1. If gross is larger than $100.00
4.1.1. Deduct the dues of $15.00 from gross pay.
else
4.1.2. Deduct no dues.
5. Display gross and net pay.
125Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
4.7 Nested if Statements and Multiple-Alternative Decisions
• Nested logic is one control structure containing another similar control structure
• E.g. one if statement inside another
• Makes it possible to code decisions with several alternatives
126Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example of Nested Logic
if (x > 0)
numPos = numPos + 1;
else
if (x < 0)
numNeg = numNeg + 1;
else // x must equal 0
numZero = numZero + 1;
127Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Example of Nested Logic
X numPos numNegnumZero
3.0 _______ _______ _______
-3.6 _______ _______ _______
0 _______ _______ _______
Assume all variables initialized to 0
128Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Comparison of Nested if to Sequence of if Statements
if (x > 0)
numPos = numPos + 1;
if (x < 0)
numNeg = numNeg + 1;
if (x == 0)
numZero = numZero + 1;
129Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Writing a Nested if as a Multiple-Alternative Decision
• Nested if statements can become quite complex. If there are more than three alternatives and indentation is not consistent, it may be difficult to determine the logical structure of the if statement.
130Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Multiple-Alternative Decision Form
if (condition1)
statement1;
else if (condition2)
statement2;.
.
.
else if (conditionn)
statementn;
else
statemente;
131Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Multiple-Alternative Example
if (x > 0)
numPos = numPos + 1;
else if (x < 0)
numNeg = numNeg + 1;
else
numZero = numZero + 1;
132Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Function displayGrade
void displayGrade (int score)
{
if (score >= 90)
cout << "Grade is A " << endl;
else if (score >= 80)
cout << "Grade is B " << endl;
else if (score >= 70)
cout << "Grade is C " << endl;
else if (score >= 60)
cout << "Grade is D " << endl;
else
cout << "Grade is F " << endl;
}
133Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Order of Conditions Matters
if (score >= 60)
cout << "Grade is D " << endl;
else if (score >= 70)
cout << "Grade is C " << endl;
else if (score >= 80)
cout << "Grade is B " << endl;
else if (score >= 90)
cout << "Grade is A " << endl;
else
cout << "Grade is F " << endl;
134Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Table 4.12 Decision Table for Example 4.16
135Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Listing 4.4 Function computeTax
136Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Short Circuit Evaluation
(single == ‘y’ && gender == ‘m’ && age >= 18) – If single is false, gender and age are not
evaluated
(single == ‘y’ || gender == ‘m’ || age >= 18)– If single is true, gender and age are not
evaluated
137
Thank You
For
Your Attention!