Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Lecture 10: Control Flow. Selection (Decision) structures."— Presentation transcript:

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

2 2 Lecture Contents: t Quiz on C++ Functions t The if statement (“then” version) t The if statement (“then – else” version) t Nested if...else statements versus sequence of if statements t Demo programs t Exercises

3 3 Quiz #2 on C++ Functions

4 4 4. Control Structures t Three methods of processing a program –In sequence –Branching –Looping t Branch: altering the flow of program execution by making a selection or choice t Loop: altering the flow of program execution by repetition of statement(s)

5 5 5. Flow of Execution

6 6 The if statement (“then” version) Syntax and flowchart fragment: if ( ) ;

7 7 The if statement (“then” – else version) Syntax and flowchart fragment: if ( ) ; else ;

8 8 Nested if…else statements vs. sequence of if statements t Nested if … else … statements. t 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; t The rule: An else is matched with the last if that doesn’t have its own else.

9 9 Nested if…else statements vs. sequence of if statements t 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 x if (x > 0)n_pos = n_pos + 1; else if (x < 0)n_neg = n_neg + 1; else n_zero = n_zero + 1;

10 10 Nested if…else statements vs. sequence of if statements t Sequence of if statements Example: // 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; if ( x == 0 )n_zero = n_zero + 1; // less efficient version because all // three conditions are always tested

11 11 Else If clause A 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 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 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 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 15 More on if statement(s) Extract from Friedman/Koffman, chapter 4

16 Selection Structures: if and switch Statements Chapter 4

17 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 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 19 4.2 Logical Expressions

20 20 Boolean Variables t bool variable t Included with C++ compiler bool leapYear; leapYear = true;// Non zero return value leapYear = false;// Zero return value

21 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 22 Logical Expressions –Logical expressions often use these relational operators:

23 23 Logical Operators t Logical operator (&& means AND) used in an if...else statement: ( (tryIt >= 50) && (tryIt <= 1500) ) t Logical operator (| | means OR) used in an if...else statement: ( (tryIt 1500) )

24 24 Using && t Assume tryIt = 90, t Is tryIt within the range of 50 and 1500 ? ( (tryIt >= 50) && (tryIt <= 1500) ) ( ( 90 >= 50) && ( 90 <= 1500) ) ( 1 && 1 ) 1

25 25 Using || t Assume tryIt = 99 t Is tryIt outside the range of 50 and 1500 ? ( (tryIt 1500) ) ( ( 99 1500) ) ( 0 || 0 ) 0

26 26 Truth Tables for Boolean Operators t 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

27 27 Truth Tables for Boolean Operators or Logical Functions t Boolean operators = Logical functions t Arguments are logical/boolean values – false/true or 0/1 t Unary logical NOT function, denoted ! ArgFunction 01!0 = 1 10!1 = 0

28 28 Truth Tables for Boolean Operators or Logical Functions t Boolean operators = Logical functions t Arguments are logical/boolean values –false/true or 0/1 t Binary logical AND function, denoted &&,a && b Arg1 Arg2Function 0 00 0 && 0 = 0 0 100 && 1 = 0 1 001 && 0 = 0 1 111 && 1 = 1

29 29 Truth Tables for Boolean Operators or Logical Functions t Boolean operators = Logical functions t Arguments are logical/boolean values –false/true or 0/1 t Binary logical OR function, denoted ||,a || b Arg1 Arg2Function 0 00 0 || 0 = 0 0 110 || 1 = 1 1 011 || 0 = 1 1 111 || 1 = 1

30 30 Truth Tables for Boolean Operators or Logical Functions t Boolean operators = Logical functions t Arguments are logical/boolean values –false/true or 0/1  Binary logical EOR function, denoted ,a  b Arg1 Arg2Function 0 00 0  0 = 0 0 110  1 = 1 1 011  0 = 1 1 101  1 = 0

31 31 Bit-wise logical operators t &- bit wise AND operator t |- bit wise OR operator

32 32 De Morgan laws t 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.logicformal logiclogical operatorsnegation t Augustus De Morgan originally observed that in classical propositional logic the following relationships hold: Augustus De Morganpropositional logic t not (P and Q) = (not P) or (not Q) t not (P or Q) = (not P) and (not Q)

33 33 Boolean Algebra t Full set of boolean binary functions ArgsFunctions a e a b n o o d r r 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

34 34 Boolean Algebra t Minimal /basic/ set of boolean functions –Negation or logical not not a!a –Conjunction or logical multiplication a and ba && b –Disjunction or logical addition a or ba || b

35 35 Boolean Algebra t Exclusive OR formulated through basic functions t a  b = (not a and b) or (a and not b) t a  b = (!a && b) || (a && !b)

36 36 Precedence of Operators t Precedence: most operators are evaluated (grouped) in a left-to-right order: – a / b / c / d is equivalent to (((a/b)/c)/d) t 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 37 Precedence of Operators

38 38 Boolean Assignment bool same; same = true; Form:variable = expression; Example:same = (x = = y);

39 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 40 if Control Statements with 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 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 42 Programming Tip t Using = for == is a common mistake. For example the following statements are legal: t 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 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 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 45 4.6 Checking the Correctness of an Algorithm t 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 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 47 Example of nested logic if(x > 0) numPos = numPos + 1; else if(x < 0) numNeg = NumNeg + 1; else numZero = numZero + 1;

48 48 Example of nested logic XnumPos numNegnumZero 3.0_____________________ -3.6_____________________ 4.0_____________________ Assume all variables initialized to 0

49 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 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 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 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 53 4.9 Common Programming Errors t 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 >>>

54 54 Common Programming Errors t 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"; t 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 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 56 Exercise 10.1 Build programs based on branch algorithms: t To add, subtract, multiply, and divide two integer values checking the valid divisor (!=0) condition

57 57 Exercise 10.2 Build programs based on branch algorithms: t To associate noise loudness with the effect of noise using a table data: Loudness in decibels(db)Perception 50 or lowerquiet 51-90annoying 91-110very annoying Above 110uncomfortable

58 58 Exercise 10.3 Build programs based on branch algorithms:  To implement nested if statements using sample flow chart algorithms

59 59 Exercise 10.4 Build programs based on branch algorithms:  To compute area of a triangle by Heron’s formulae

60 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 61 Exercise 10.6 Build programs based on branch algorithms:  To find roots (solutions) of a linear equation bx + c = 0

62 62 Exercise 10.7 Build programs based on branch algorithms: t To find roots (solutions) of a quadratic equation ax 2 + bx + c = 0

63 63 Before lecture end Lecture: Control Flow. Selection (decision) structures More to read: Friedman/Koffman, Chapter 04

64 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

65 65 Copyright © 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

66 66 Copyright © 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

67 67 Copyright © 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: { statement 1 ; statement 2 ;. statement n ; }

68 68 Copyright © 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;

69 69 Copyright © 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

70 70 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.1 Rational and Equality Operators

71 71 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example x x <= 0 -5 true

72 72 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example xy x >= y -5 false 7 7

73 73 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Logical Operators && (and) || (or) ! (not) Used to form more complex conditions, e.g. (salary 5) (temperature > 90.0) && (humidity > 0.90) winningRecord && (!probation)

74 74 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.3 && Operator

75 75 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.4 || Operator

76 76 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.5 ! Operator

77 77 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.6 Operator Precedence

78 78 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example flagxyz 3.04.02.0false x + y / z <= 3.5 2.0 5.0 false

79 79 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example flagxyz 3.04.02.0false ! flag || (y + z >= x - z) 6.01.0 true

80 80 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.7 English Conditions as C++ Expressions

81 81 Copyright © 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

82 82 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.8 Examples of Comparisons

83 83 Copyright © 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);

84 84 Copyright © 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);

85 85 Copyright © 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

86 86 Copyright © 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

87 87 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if Statement with Two Alternatives Form: if (condition) statement T else statement F E.g.: if (gross > 100.00) net = gross - tax; else net = gross;

88 88 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 4.4 Flowchart of if statement with two alternatives

89 89 Copyright © 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) statement T E.g.:if (x != 0) product = product * x;

90 90 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 4.5 Flowchart of if statement with a dependent

91 91 Copyright © 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

92 92 Copyright © 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; }

93 93 Copyright © 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; }

94 94 Copyright © 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.

95 95 Copyright © 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

96 96 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.9 Step-by-Step Hand Trace of if statement

97 97 Copyright © 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

98 98 Copyright © 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.

99 99 Copyright © 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.

100 100 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Data Requirements Problem Constants MAX_NO_DUES = 100.00 DUES = 15.00 MAX_NO_OVERTIME = 40.0 OVERTIME_RATE = 1.5

101 101 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Data Requirements Problem Input float hours float rate Problem Output float gross float net

102 102 Copyright © 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.

103 103 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 4.6 Structure chart for payroll problem

104 104 Copyright © 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.

105 105 Copyright © 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

106 106 Copyright © 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.

107 107 Copyright © 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

108 108 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: computeGross Function Formula Gross pay = Hours worked  Hourly pay Local Data float gross float regularPay float overtimePay

109 109 Copyright © 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

110 110 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: computeNet Function Interface –Input Arguments float gross –Function Return Value float net Formula net pay = gross pay - deductions Local Data float net

111 111 Copyright © 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

112 112 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.1 Payroll problem with functions

113 113 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.1 Payroll problem with functions (continued)

114 114 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.1 Payroll problem with functions (continued)

115 115 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.1 Payroll problem with functions (continued)

116 116 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.1 Payroll problem with functions (continued)

117 117 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.2 Sample run of payroll program with functions

118 118 Copyright © 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

119 119 Copyright © 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.

120 120 Copyright © 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.

121 121 Copyright © 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

122 122 Copyright © 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

123 123 Copyright © 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.

124 124 Copyright © 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.

125 125 Copyright © 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

126 126 Copyright © 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;

127 127 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example of Nested Logic XnumPosnumNegnumZero 3.0_____________________ -3.6_____________________ 0_____________________ Assume all variables initialized to 0

128 128 Copyright © 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;

129 129 Copyright © 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.

130 130 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Multiple-Alternative Decision Form if (condition 1 ) statement 1 ; else if (condition 2 ) statement 2 ;. else if (condition n ) statement n ; else statement e ;

131 131 Copyright © 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;

132 132 Copyright © 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; }

133 133 Copyright © 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;

134 134 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.12 Decision Table for Example 4.16

135 135 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.4 Function computeTax

136 136 Copyright © 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 137 Thank You For Your Attention!


Download ppt "Lecture 10: Control Flow. Selection (Decision) structures."

Similar presentations


Ads by Google