Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving,

Similar presentations


Presentation on theme: "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving,"— Presentation transcript:

1 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++ 6e by Frank L. Friedman and Elliot B. Koffman

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

74 74 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.8 The switch Control Statement switch ( switch-expression ) { case label 1 : statements 1 ; break; case label 2 : statements 2 ; break;. case label n : statements n ; break; default: statements d ; // optional }

75 75 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Switch Control Statement Alternative to multiple if statements in some cases Most useful when switch selector is single variable or simple expression Switch selector must be an integral type (int, char, bool)

76 76 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Switch Control Statement Switch selector value compared to each case label. When there is an exact match, statements for that case are executed. If no case label matches the selector, the entire switch body is skipped unless it contains a default case label. break is typically used between cases to avoid fall through.

77 77 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.5 switch statement to determine life expectancy of a lightbulb

78 78 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4.9 Common Programming Errors Use parentheses to clarify complex expressions Use logical operators only with logical expressions Use brackets { } to group multiple statements for use in control structures

79 79 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Common Programming Errors When writing a nested if statement, use multiple-alternative form if possible –if conditions are not mutually exclusive, put the most restrictive condition first Make sure switch selector and case labels are the same type. Provide a default case for a switch statement whenever possible.


Download ppt "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving,"

Similar presentations


Ads by Google