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

Slides:



Advertisements
Similar presentations
Chapter 4 Selection Structures: if and switch Statements Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering.
Advertisements

Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
CONTROL STRUCTURES: SEQUENTIAL, SELECTIVE, AND REPETITIVE
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 CS 201 Selection Structures (1) Debzani Deb. 2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable.
C++ for Engineers and Scientists Third Edition
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Structural Program Development: If, If-Else Outline.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4 Selection Structures: if and switch Statements Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CPS120: Introduction to Computer Science Decision Making in Programs.
Selection Structures: if and switch Statements Chapter 4.
Lecture 10: Control Flow. Selection (Decision) structures.
A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Flow of Control Part 1: Selection
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Selection Structures: if and switch Statements. 2 Selection Statements –In this chapter we study statements that allow alternatives to straight sequential.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Week 4 Program Control Structure
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
CPS120: Introduction to Computer Science Decision Making in Programs.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
A First Book of C++ Chapter 4 Selection.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Branching statements.
The if…else Selection Statement
Chapter 3 Control Statements
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
EGR 2261 Unit 4 Control Structures I: Selection
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 7 Conditional Statements
Chapter 6 Control Statements: Part 2
Chapter 4 Selection.
Chapter 4: Control Structures I (Selection)
Decision I (if Statement)
Chapter 4: Selection Structures: if and switch Statements
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

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 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 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 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 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 > ) shipCost = 10.00; else shipCost = 5.00;

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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.1 Rational and Equality Operators

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

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

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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.3 && Operator

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

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

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

15 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example flagxyz false x + y / z <= false

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

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

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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.8 Examples of Comparisons

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 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 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 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 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 > ) net = gross - tax; else net = gross;

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

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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 4.5 Flowchart of if statement with a dependent

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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example 4.11 if (popToday > popYesterday) { growth = popToday - popYesterday; growthPct = * growth / popYesterday; cout << “The growth percentage is “ << growthPct; }

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 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 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.9 Step-by-Step Hand Trace of if statement

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 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 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: Data Requirements Problem Constants MAX_NO_DUES = DUES = MAX_NO_OVERTIME = 40.0 OVERTIME_RATE = 1.5

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 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 4.6 Structure chart for payroll problem

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 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 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 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 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 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) Compute regularPay Compute overtimePay Add regularPay to overtimePay to get gross Else Compute gross as house * rate

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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Case Study: computeNet Function - Algorithm 4.1 If the gross pay is larger than $ Deduct the dues of $15 from gross pay Else Deduct no dues

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

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

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

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

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

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

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 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 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 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 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 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 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example - Trace of Payroll Problem 4. Compute net pay If gross is larger than $ Deduct the dues of $15.00 from gross pay. else Deduct no dues. 5. Display gross and net pay.

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 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 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 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 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 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 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 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 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 4.12 Decision Table for Example 4.16

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

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 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 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 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 4.5 switch statement to determine life expectancy of a lightbulb

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