Lecture 10: Control Flow. Selection (Decision) structures.

137
Lecture 10: Control Flow. Selection (Decision) structures

Transcript of Lecture 10: Control Flow. Selection (Decision) structures.

Page 1: Lecture 10: Control Flow. Selection (Decision) structures.

Lecture 10: Control Flow. Selection (Decision) structures

Page 2: 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

Page 3: Lecture 10: Control Flow. Selection (Decision) structures.

3

Quiz #2on

C++ Functions

Page 4: Lecture 10: Control Flow. Selection (Decision) structures.

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)

Page 5: Lecture 10: Control Flow. Selection (Decision) structures.

55.

Flow of Execution

Page 6: Lecture 10: Control Flow. Selection (Decision) structures.

6

The if statement (“then” version)

Syntax and flowchart fragment:

if (<expression>) <statement>;

Page 7: Lecture 10: Control Flow. Selection (Decision) structures.

7

The if statement (“then” – else version)

Syntax and flowchart fragment:

if (<expression>) <statement_1>;

else <statement_2>;

Page 8: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 9: Lecture 10: Control Flow. Selection (Decision) structures.

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;

Page 10: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 11: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 12: Lecture 10: Control Flow. Selection (Decision) structures.

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”;

Page 13: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 14: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 15: Lecture 10: Control Flow. Selection (Decision) structures.

15

More on if statement(s)

Extract from Friedman/Koffman, chapter 4

Page 16: Lecture 10: Control Flow. Selection (Decision) structures.

Selection Structures: if and switch Statements

Chapter 4

Page 17: Lecture 10: Control Flow. Selection (Decision) structures.

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: ||)

Page 18: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 19: Lecture 10: Control Flow. Selection (Decision) structures.

19

4.2 Logical Expressions

Declarationint month = 9;Expression is(month > 9) False

(month < 9) False

(month >= 9) True

(month <= 9) True

Page 20: Lecture 10: Control Flow. Selection (Decision) structures.

20

Boolean Variables

bool variable Included with C++ compiler

bool leapYear;

leapYear = true; // Non zero return value

leapYear = false; // Zero return value

Page 21: Lecture 10: Control Flow. Selection (Decision) structures.

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 // _____

Page 22: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 23: Lecture 10: Control Flow. Selection (Decision) structures.

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) )

Page 24: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 25: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 26: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 27: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 28: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 29: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 30: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 31: Lecture 10: Control Flow. Selection (Decision) structures.

31

Bit-wise logical operators

& - bit wise AND operator | - bit wise OR operator

Page 32: Lecture 10: Control Flow. Selection (Decision) structures.

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)

Page 33: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 34: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 35: Lecture 10: Control Flow. Selection (Decision) structures.

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)

Page 36: Lecture 10: Control Flow. Selection (Decision) structures.

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)))

Page 37: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 38: Lecture 10: Control Flow. Selection (Decision) structures.

38

Boolean Assignment

bool same;

same = true;

Form: variable = expression;

Example: same = (x = = y);

Page 39: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 40: Lecture 10: Control Flow. Selection (Decision) structures.

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 ;

Page 41: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 42: Lecture 10: Control Flow. Selection (Decision) structures.

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)

Page 43: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 44: Lecture 10: Control Flow. Selection (Decision) structures.

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;}

Page 45: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 46: Lecture 10: Control Flow. Selection (Decision) structures.

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):

Page 47: Lecture 10: Control Flow. Selection (Decision) structures.

47

Example of nested logic

if(x > 0)

numPos = numPos + 1;

else

if(x < 0)

numNeg = NumNeg + 1;

else

numZero = numZero + 1;

Page 48: Lecture 10: Control Flow. Selection (Decision) structures.

48

Example of nested logic

X numPos numNeg numZero

3.0 _______ _______ _______

-3.6 _______ _______ _______

4.0 _______ _______ _______

Assume all variables initialized to 0

Page 49: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 50: Lecture 10: Control Flow. Selection (Decision) structures.

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;

}

Page 51: Lecture 10: Control Flow. Selection (Decision) structures.

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;

Page 52: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 53: Lecture 10: Control Flow. Selection (Decision) structures.

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 >>>>

Page 54: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 55: Lecture 10: Control Flow. Selection (Decision) structures.

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";}

Page 56: Lecture 10: Control Flow. Selection (Decision) structures.

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       

Page 57: Lecture 10: Control Flow. Selection (Decision) structures.

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       

Page 58: Lecture 10: Control Flow. Selection (Decision) structures.

58

Exercise 10.3

Build programs based on branch algorithms:

To implement nested if statements using sample flow chart algorithms

Page 59: Lecture 10: Control Flow. Selection (Decision) structures.

59

Exercise 10.4

Build programs based on branch algorithms:

  

 To compute area of a triangle by Heron’s formulae

Page 60: Lecture 10: Control Flow. Selection (Decision) structures.

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)

Page 61: Lecture 10: Control Flow. Selection (Decision) structures.

61

Exercise 10.6

Build programs based on branch algorithms:

 To find roots (solutions) of a linear equation bx + c = 0

Page 62: Lecture 10: Control Flow. Selection (Decision) structures.

62

Exercise 10.7

Build programs based on branch algorithms:

To find roots (solutions) of a quadratic equation ax2 + bx + c = 0

Page 63: Lecture 10: Control Flow. Selection (Decision) structures.

63

Before lecture end

Lecture:

Control Flow. Selection (decision) structures

More to read:

Friedman/Koffman, Chapter 04

Page 64: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 65: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 66: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 67: Lecture 10: Control Flow. Selection (Decision) structures.

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;}

Page 68: Lecture 10: Control Flow. Selection (Decision) structures.

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;

Page 69: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 70: Lecture 10: Control Flow. Selection (Decision) structures.

70Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table 4.1 Rational and Equality Operators

Page 71: Lecture 10: Control Flow. Selection (Decision) structures.

71Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Example

x

x <= 0

-5

-5

true

Page 72: Lecture 10: Control Flow. Selection (Decision) structures.

72Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Example

x y

x >= y

-5

-5

false

7

7

Page 73: Lecture 10: Control Flow. Selection (Decision) structures.

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)

Page 74: Lecture 10: Control Flow. Selection (Decision) structures.

74Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table 4.3 && Operator

Page 75: Lecture 10: Control Flow. Selection (Decision) structures.

75Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table 4.4 || Operator

Page 76: Lecture 10: Control Flow. Selection (Decision) structures.

76Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table 4.5 ! Operator

Page 77: Lecture 10: Control Flow. Selection (Decision) structures.

77Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table 4.6 Operator Precedence

Page 78: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 79: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 80: Lecture 10: Control Flow. Selection (Decision) structures.

80Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table 4.7 English Conditions as C++ Expressions

Page 81: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 82: Lecture 10: Control Flow. Selection (Decision) structures.

82Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table 4.8 Examples of Comparisons

Page 83: Lecture 10: Control Flow. Selection (Decision) structures.

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);

Page 84: Lecture 10: Control Flow. Selection (Decision) structures.

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);

Page 85: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 86: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 87: Lecture 10: Control Flow. Selection (Decision) structures.

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;

Page 88: Lecture 10: Control Flow. Selection (Decision) structures.

88Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 4.4 Flowchart of if statement with two alternatives

Page 89: Lecture 10: Control Flow. Selection (Decision) structures.

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;

Page 90: Lecture 10: Control Flow. Selection (Decision) structures.

90Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 4.5 Flowchart of if statement with a dependent

Page 91: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 92: Lecture 10: Control Flow. Selection (Decision) structures.

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;

}

Page 93: Lecture 10: Control Flow. Selection (Decision) structures.

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;

}

Page 94: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 95: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 96: Lecture 10: Control Flow. Selection (Decision) structures.

96Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table 4.9 Step-by-Step Hand Trace of if statement

Page 97: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 98: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 99: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 100: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 101: Lecture 10: Control Flow. Selection (Decision) structures.

101Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Case Study: Data Requirements

• Problem Inputfloat hours

float rate

• Problem Outputfloat gross

float net

Page 102: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 103: Lecture 10: Control Flow. Selection (Decision) structures.

103Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 4.6 Structure chart for payroll problem

Page 104: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 105: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 106: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 107: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 108: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 109: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 110: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 111: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 112: Lecture 10: Control Flow. Selection (Decision) structures.

112Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 4.1 Payroll problem with functions

Page 113: Lecture 10: Control Flow. Selection (Decision) structures.

113Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 4.1 Payroll problem with functions (continued)

Page 114: Lecture 10: Control Flow. Selection (Decision) structures.

114Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 4.1 Payroll problem with functions (continued)

Page 115: Lecture 10: Control Flow. Selection (Decision) structures.

115Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 4.1 Payroll problem with functions (continued)

Page 116: Lecture 10: Control Flow. Selection (Decision) structures.

116Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 4.1 Payroll problem with functions (continued)

Page 117: Lecture 10: Control Flow. Selection (Decision) structures.

117Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 4.2 Sample run of payroll program with functions

Page 118: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 119: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 120: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 121: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 122: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 123: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 124: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 125: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 126: Lecture 10: Control Flow. Selection (Decision) structures.

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;

Page 127: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 128: Lecture 10: Control Flow. Selection (Decision) structures.

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;

Page 129: Lecture 10: Control Flow. Selection (Decision) structures.

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.

Page 130: Lecture 10: Control Flow. Selection (Decision) structures.

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;

Page 131: Lecture 10: Control Flow. Selection (Decision) structures.

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;

Page 132: Lecture 10: Control Flow. Selection (Decision) structures.

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;

}

Page 133: Lecture 10: Control Flow. Selection (Decision) structures.

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;

Page 134: Lecture 10: Control Flow. Selection (Decision) structures.

134Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table 4.12 Decision Table for Example 4.16

Page 135: Lecture 10: Control Flow. Selection (Decision) structures.

135Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 4.4 Function computeTax

Page 136: Lecture 10: Control Flow. Selection (Decision) structures.

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

Page 137: Lecture 10: Control Flow. Selection (Decision) structures.

137

Thank You

For

Your Attention!