Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4: Selection Structures: if and switch Statements

Similar presentations


Presentation on theme: "Chapter 4: Selection Structures: if and switch Statements"— Presentation transcript:

1 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 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 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 Sequential Execution Each statement is executed in sequence.
A compound statement is used to specify sequential control: { statement1; statement2; . statementn; }

5 4.2 Logical Expressions C++ control structure for selection is the if statement. E.g.: if (weight > ) shipCost = 10.00; else shipCost = 5.00;

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 Table 4.1 Rational and Equality Operators

8 Example x x <= 0 -5 -5 true

9 Example x y x >= y -5 7 -5 7 false

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

11 Table 4.3 && Operator

12 Table 4.4 || Operator

13 Table 4.5 ! Operator

14 Table 4.6 Operator Precedence

15 Example x y z flag 3.0 4.0 2.0 false x + y / z <= 3.5 2.0 5.0 false

16 Example x y z flag 3.0 4.0 2.0 false ! flag || (y + z >= x - z)
true 6.0 1.0 true true

17 Table 4.7 English Conditions as C++ Expressions

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 Table 4.8 Examples of Comparisons

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 Additional Examples inRange = (n > -10) && (n < 10);
isLetter = ((‘A’ <= ch) && (ch <= ‘Z’)) || ((‘a’ <= ch) && (ch <= ‘z’)); even = (n % 2 == 0);

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 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 if Statement with Two Alternatives
Form: if (condition) statementT else statementF E.g.: if (gross > ) net = gross - tax; net = gross;

25 Figure 4.4 Flowchart of if statement with two alternatives

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

27 Figure 4.5 Flowchart of if statement with a dependent

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 Example 4.11 if (popToday > popYesterday) {
growth = popToday - popYesterday; growthPct = * growth / popYesterday; cout << “The growth percentage is “ << growthPct; }

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 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 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 Table 4.9 Step-by-Step Hand Trace of if statement

34 Decision Steps in Algorithms
Algorithm steps that select from a choice of actions are called decision steps Typically coded as if statements

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 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 Case Study: Data Requirements
Problem Constants MAX_NO_DUES = DUES = 15.00 MAX_NO_OVERTIME = 40.0 OVERTIME_RATE = 1.5

38 Case Study: Data Requirements
Problem Input float hours float rate Problem Output float gross float net

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 Figure 4.6 Structure chart for payroll problem

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 Case Study: instructUser Function
Global constants - declared before function main MAX_NO_DUES DUES MAX_NO_OVERTIME OVERTIME_RATE

43 Case Study: instructUser Function
Interface Input Arguments none Function Return Value Description Displays a short list of instructions and information about the program for the user.

44 Case Study: computeGross Function
Interface Input Arguments float hours float rate Function Return Value float gross

45 Case Study: computeGross Function
Formula Gross pay = Hours worked  Hourly pay Local Data float gross float regularPay float overtimePay

46 Case Study: computeGross Function - Algorithm
3.1 If the hours worked exceeds 40.0 (max hours before overtime) Compute regularPay Compute overtimePay Add regularPay to overtimePay to get gross Else Compute gross as house * rate

47 Case Study: computeNet Function
Interface Input Arguments float gross Function Return Value float net Formula net pay = gross pay - deductions Local Data

48 Case Study: computeNet Function - Algorithm
4.1 If the gross pay is larger than $100.00 Deduct the dues of $15 from gross pay Else Deduct no dues

49 Listing 4.1 Payroll problem with functions

50 Listing 4.1 Payroll problem with functions (continued)

51 Listing 4.1 Payroll problem with functions (continued)

52 Listing 4.1 Payroll problem with functions (continued)

53 Listing 4.1 Payroll problem with functions (continued)

54 Listing 4.2 Sample run of payroll program with functions

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 Identifier Scope Variable gross in main function
Local variable gross in function computeGross. No direct connection between these variables.

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 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 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 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) Compute regularPay. Compute overtimePay. Add regularPay to overtimePay to get gross. else Compute gross as hours * rate.

61 Example - Trace of Payroll Problem
4. Compute net pay. 4.1. If gross is larger than $100.00 Deduct the dues of $15.00 from gross pay. else Deduct no dues. 5. Display gross and net pay.

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 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 Example of Nested Logic
X numPos numNeg numZero 3.0 _______ _______ _______ -3.6 _______ _______ _______ 0 _______ _______ _______ Assume all variables initialized to 0

65 Comparison of Nested if to Sequence of if Statements
if (x > 0) numPos = numPos + 1; if (x < 0) numNeg = numNeg + 1; numZero = numZero + 1;

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 Multiple-Alternative Decision Form
if (condition1) statement1; else if (condition2) statement2; . else if (conditionn) statementn; else statemente;

68 Multiple-Alternative Example
if (x > 0) numPos = numPos + 1; else if (x < 0) numNeg = numNeg + 1; else numZero = numZero + 1;

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 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 Table 4.12 Decision Table for Example 4.16

72 Listing 4.4 Function computeTax

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 4.8 The switch Control Statement
switch ( switch-expression ) { case label1: statements1; break; case label2: statements2; ... case labeln: statementsn; default: statementsd; // optional but highly recommended }

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 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 Listing 4.5 switch statement to determine life expectancy of a lightbulb

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

Similar presentations


Ads by Google