Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville.

Similar presentations


Presentation on theme: "Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville."— Presentation transcript:

1 Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551 bliffick@millersville.edu

2 © 2004 Pearson Addison-Wesley. All rights reserved4-2 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 © 2004 Pearson Addison-Wesley. All rights reserved4-3 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 © 2004 Pearson Addison-Wesley. All rights reserved4-4 Sequential Execution Each statement is executed in sequence. A compound statement is used to specify sequential control: { statement 1 ; statement 2 ;. statement n ; }

5 © 2004 Pearson Addison-Wesley. All rights reserved4-5 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 © 2004 Pearson Addison-Wesley. All rights reserved4-6 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 © 2004 Pearson Addison-Wesley. All rights reserved4-7 Table 4.1 Rational and Equality Operators

8 © 2004 Pearson Addison-Wesley. All rights reserved4-8 Example x x <= 0 -5 true

9 © 2004 Pearson Addison-Wesley. All rights reserved4-9 Example xy x >= y -5 false 7 7

10 © 2004 Pearson Addison-Wesley. All rights reserved4-10 Logical Operators && (and) || (or) ! (not) Used to form more complex conditions, e.g. (salary 5) (temperature > 90.0) && (humidity > 0.90) winningRecord && (!probation)

11 © 2004 Pearson Addison-Wesley. All rights reserved4-11 Table 4.3 && Operator

12 © 2004 Pearson Addison-Wesley. All rights reserved4-12 Table 4.4 || Operator

13 © 2004 Pearson Addison-Wesley. All rights reserved4-13 Table 4.5 ! Operator

14 © 2004 Pearson Addison-Wesley. All rights reserved4-14 Table 4.6 Operator Precedence

15 © 2004 Pearson Addison-Wesley. All rights reserved4-15 Example flagxyz 3.04.02.0false x + y / z <= 3.5 2.0 5.0 false

16 © 2004 Pearson Addison-Wesley. All rights reserved4-16 Example flagxyz 3.04.02.0false ! flag || (y + z >= x - z) 6.01.0 true

17 © 2004 Pearson Addison-Wesley. All rights reserved4-17 Table 4.7 English Conditions as C++ Expressions

18 © 2004 Pearson Addison-Wesley. All rights reserved4-18 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 © 2004 Pearson Addison-Wesley. All rights reserved4-19 Table 4.8 Examples of Comparisons

20 © 2004 Pearson Addison-Wesley. All rights reserved4-20 Boolean Assignment Assignment statements have general form variable = expression; E.g.: (for variable called same of type bool) same = true; same = (x == y);

21 © 2004 Pearson Addison-Wesley. All rights reserved4-21 Additional Examples inRange = (n > -10) && (n < 10); isLetter = ((‘A’ <= ch) && (ch <= ‘Z’)) || ((‘a’ <= ch) && (ch <= ‘z’)); even = (n % 2 == 0);

22 © 2004 Pearson Addison-Wesley. All rights reserved4-22 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 © 2004 Pearson Addison-Wesley. All rights reserved4-23 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 © 2004 Pearson Addison-Wesley. All rights reserved4-24 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 © 2004 Pearson Addison-Wesley. All rights reserved4-25 Figure 4.4 Flowchart of if statement with two alternatives

26 © 2004 Pearson Addison-Wesley. All rights reserved4-26 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 © 2004 Pearson Addison-Wesley. All rights reserved4-27 Figure 4.5 Flowchart of if statement with a dependent

28 © 2004 Pearson Addison-Wesley. All rights reserved4-28 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 © 2004 Pearson Addison-Wesley. All rights reserved4-29 Example 4.11 if (popToday > popYesterday) { growth = popToday - popYesterday; growthPct = 100.0 * growth / popYesterday; cout << “The growth percentage is “ << growthPct; }

30 © 2004 Pearson Addison-Wesley. All rights reserved4-30 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 © 2004 Pearson Addison-Wesley. All rights reserved4-31 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 © 2004 Pearson Addison-Wesley. All rights reserved4-32 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 © 2004 Pearson Addison-Wesley. All rights reserved4-33 Table 4.9 Step-by-Step Hand Trace of if statement

34 © 2004 Pearson Addison-Wesley. All rights reserved4-34 Decision Steps in Algorithms Algorithm steps that select from a choice of actions are called decision steps Typically coded as if statements

35 © 2004 Pearson Addison-Wesley. All rights reserved4-35 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 © 2004 Pearson Addison-Wesley. All rights reserved4-36 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 © 2004 Pearson Addison-Wesley. All rights reserved4-37 Case Study: Data Requirements Problem Constants MAX_NO_DUES = 100.00 DUES = 15.00 MAX_NO_OVERTIME = 40.0 OVERTIME_RATE = 1.5

38 © 2004 Pearson Addison-Wesley. All rights reserved4-38 Case Study: Data Requirements Problem Input float hours float rate Problem Output float gross float net

39 © 2004 Pearson Addison-Wesley. All rights reserved4-39 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 © 2004 Pearson Addison-Wesley. All rights reserved4-40 Figure 4.6 Structure chart for payroll problem

41 © 2004 Pearson Addison-Wesley. All rights reserved4-41 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 © 2004 Pearson Addison-Wesley. All rights reserved4-42 Case Study: instructUser Function Global constants - declared before function main MAX_NO_DUES DUES MAX_NO_OVERTIME OVERTIME_RATE

43 © 2004 Pearson Addison-Wesley. All rights reserved4-43 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 © 2004 Pearson Addison-Wesley. All rights reserved4-44 Case Study: computeGross Function Interface –Input Arguments float hours float rate –Function Return Value float gross

45 © 2004 Pearson Addison-Wesley. All rights reserved4-45 Case Study: computeGross Function Formula Gross pay = Hours worked  Hourly pay Local Data float gross float regularPay float overtimePay

46 © 2004 Pearson Addison-Wesley. All rights reserved4-46 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 © 2004 Pearson Addison-Wesley. All rights reserved4-47 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 © 2004 Pearson Addison-Wesley. All rights reserved4-48 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 © 2004 Pearson Addison-Wesley. All rights reserved4-49 Listing 4.1 Payroll problem with functions

50 © 2004 Pearson Addison-Wesley. All rights reserved4-50 Listing 4.1 Payroll problem with functions (continued)

51 © 2004 Pearson Addison-Wesley. All rights reserved4-51 Listing 4.1 Payroll problem with functions (continued)

52 © 2004 Pearson Addison-Wesley. All rights reserved4-52 Listing 4.1 Payroll problem with functions (continued)

53 © 2004 Pearson Addison-Wesley. All rights reserved4-53 Listing 4.1 Payroll problem with functions (continued)

54 © 2004 Pearson Addison-Wesley. All rights reserved4-54 Listing 4.2 Sample run of payroll program with functions

55 © 2004 Pearson Addison-Wesley. All rights reserved4-55 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 © 2004 Pearson Addison-Wesley. All rights reserved4-56 Identifier Scope Variable gross in main function Local variable gross in function computeGross. No direct connection between these variables.

57 © 2004 Pearson Addison-Wesley. All rights reserved4-57 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 © 2004 Pearson Addison-Wesley. All rights reserved4-58 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 © 2004 Pearson Addison-Wesley. All rights reserved4-59 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 © 2004 Pearson Addison-Wesley. All rights reserved4-60 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 © 2004 Pearson Addison-Wesley. All rights reserved4-61 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 © 2004 Pearson Addison-Wesley. All rights reserved4-62 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 © 2004 Pearson Addison-Wesley. All rights reserved4-63 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 © 2004 Pearson Addison-Wesley. All rights reserved4-64 Example of Nested Logic XnumPosnumNegnumZero 3.0_____________________ -3.6_____________________ 0_____________________ Assume all variables initialized to 0

65 © 2004 Pearson Addison-Wesley. All rights reserved4-65 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 © 2004 Pearson Addison-Wesley. All rights reserved4-66 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 © 2004 Pearson Addison-Wesley. All rights reserved4-67 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 © 2004 Pearson Addison-Wesley. All rights reserved4-68 Multiple-Alternative Example if (x > 0) numPos = numPos + 1; else if (x < 0) numNeg = numNeg + 1; else numZero = numZero + 1;

69 © 2004 Pearson Addison-Wesley. All rights reserved4-69 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 © 2004 Pearson Addison-Wesley. All rights reserved4-70 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 © 2004 Pearson Addison-Wesley. All rights reserved4-71 Table 4.12 Decision Table for Example 4.16

72 © 2004 Pearson Addison-Wesley. All rights reserved4-72 Listing 4.4 Function computeTax

73 © 2004 Pearson Addison-Wesley. All rights reserved4-73 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 © 2004 Pearson Addison-Wesley. All rights reserved4-74 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 © 2004 Pearson Addison-Wesley. All rights reserved4-75 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 © 2004 Pearson Addison-Wesley. All rights reserved4-76 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 © 2004 Pearson Addison-Wesley. All rights reserved4-77 Listing 4.5 switch statement to determine life expectancy of a lightbulb

78 © 2004 Pearson Addison-Wesley. All rights reserved4-78 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 © 2004 Pearson Addison-Wesley. All rights reserved4-79 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 "Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville."

Similar presentations


Ads by Google