7-1 computing fundamentals with c++ object-oriented programming and design, 2nd edition rick mercer...

Post on 03-Jan-2016

219 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

7-1

Computing Fundamentals with C++Computing Fundamentals with C++Object-Oriented Programming and Design, 2nd EditionObject-Oriented Programming and Design, 2nd Edition

Rick MercerRick Mercer

Franklin, Beedle & Associates, 1999Franklin, Beedle & Associates, 1999

ISBN 1-887902-36-8ISBN 1-887902-36-8

Presentation Copyright 1999, Franklin, Beedle & Associates Presentation Copyright 1999, Franklin, Beedle & Associates Students who purchase and instructors who adopt Students who purchase and instructors who adopt Computing Fundamentals with C++, Computing Fundamentals with C++, Object-Oriented Programming and Design Object-Oriented Programming and Design by Rick Mercer are welcome to use this by Rick Mercer are welcome to use this

presentation as long as this copyright notice remains intact.presentation as long as this copyright notice remains intact.

7-2Chapter 7Chapter 7SelectionsSelections

In this chapter we study algorithmic patterns In this chapter we study algorithmic patterns that allow alternatives to straight sequential that allow alternatives to straight sequential processing. In particular:processing. In particular:

Guarded ActionGuarded Action execute an action only under certain conditionsexecute an action only under certain conditions

Alternative ActionAlternative Action choose one action or anotherchoose one action or another

Multiple SelectionMultiple Selection choose from more than two sets of actionschoose from more than two sets of actions

7-3 Chapter Objectives: Part IChapter Objectives: Part I

Recognize when to use Guarded ActionRecognize when to use Guarded Action Implement Guarded Action pattern with Implement Guarded Action pattern with ifif Use relational (<) and equality (==) operatorsUse relational (<) and equality (==) operators Create and evaluate expressions with logical Create and evaluate expressions with logical

operators notoperators not ! ! , and , and &&&& , or , or |||| Use Use boolbool Understand the Alternative Action PatternUnderstand the Alternative Action Pattern Implement Alternative Action with if…elseImplement Alternative Action with if…else

– ExercisesExercises

– Programming ProjectsProgramming Projects

7-4 Chapter Objectives: Part IIChapter Objectives: Part II

Choose one action from many (more than 2) Choose one action from many (more than 2) using the if…else and switch statementsusing the if…else and switch statements

Solve problems using multiple selectionSolve problems using multiple selection ExercisesExercises Programming ProjectsProgramming Projects

Note: There are two sets of exercises and programming Note: There are two sets of exercises and programming projectsprojects

7-5 Why do we need selection?Why do we need selection?

Programs must often anticipate a variety of Programs must often anticipate a variety of situationssituations

Consider an Automated Teller Machine:Consider an Automated Teller Machine: ATMs must serve valid bank customers. They ATMs must serve valid bank customers. They

must also reject invalid PINs. must also reject invalid PINs. The code that controls an ATM must permit these The code that controls an ATM must permit these

different requests. different requests. Software developers must implement code that Software developers must implement code that

anticipates all possible transactions. anticipates all possible transactions.

7-6 7.1 Selective Control7.1 Selective Control

Programs often contain statements that may Programs often contain statements that may not always executenot always execute

Sometimes a statement may execute and other Sometimes a statement may execute and other certain conditions it may notcertain conditions it may not

Reject invalid PIN entries at an ATMReject invalid PIN entries at an ATM

We say an action is guarded from executingWe say an action is guarded from executing

7-7 7.1.1 The Guarded Action Pattern7.1.1 The Guarded Action Pattern

Pattern: Guarded Action

Problem: Execute an action only under certain conditions

General if( logical-expression )

Form: true-part

Code if(aStudent.GPA() >= 3.5)Example: deansList.push_back(aStudent);

7-8 7.1.2 The if statement7.1.2 The if statement

The The ifif is the first statement that alters strict is the first statement that alters strict sequential control. General form of the if:sequential control. General form of the if:

if (if ( logical-expressionlogical-expression )) true-parttrue-part ;;

logical-expressionlogical-expression: any expression that evaluates : any expression that evaluates to nonzero (true) or zero (false)to nonzero (true) or zero (false)

In C++, almost everything is true or falseIn C++, almost everything is true or false

7-9What happens when an if What happens when an if statement executes?statement executes?

After the logical expression of the if statement After the logical expression of the if statement evaluates, the true-part executes only if the logical evaluates, the true-part executes only if the logical expression is true.expression is true.

logicalexpression

False

statement -1

statement-n

TruePart

7-10 Example if statementExample if statement

double hours = 38.0;double hours = 38.0; // Add 1.5 hours for hours over 40.0 (overtime)// Add 1.5 hours for hours over 40.0 (overtime) if(hours > 40.0)if(hours > 40.0) hours = 40.0 + 1.5 * (hours - 40.0); hours = 40.0 + 1.5 * (hours - 40.0);

Write last value of hours when it starts as:Write last value of hours when it starts as: double hours = 38.0; ____________double hours = 38.0; ____________

double hours = 40.0; ____________double hours = 40.0; ____________

double hours = 42.0; ____________double hours = 42.0; ____________

Optional Demo Optional Demo awards.cppawards.cpp demontrates the variety of program demontrates the variety of program execution when the if statement is usedexecution when the if statement is used

7-11 Another wayAnother way

The if statement could also be written with a The if statement could also be written with a block as the true part: block as the true part: here it is not necessary here it is not necessary

if(hours > 40.0)if(hours > 40.0) {{ hours = 40.0 + 1.5 * (hours - 40.0); hours = 40.0 + 1.5 * (hours - 40.0); }}

Sometimes the block is required Sometimes the block is required consider using consider using { }{ }

if(hours > 40.0)if(hours > 40.0) {{ regularHours = 40.0;regularHours = 40.0; overtimeHours = hours - 40.0;overtimeHours = hours - 40.0; }}

7-127.2 Logical expressions with 7.2 Logical expressions with Relational Operators Relational Operators

Logical expressions often use these relational Logical expressions often use these relational operators:operators:

> Greater than< Less than>= Greater than or equal<= Less than or equal== Equal!= Not equal

7-13 Logical ExpressionsLogical Expressions

Examples (Write T for True, or F for False):Examples (Write T for True, or F for False): int n1 = 78;int n1 = 78;

int n2 = 80;int n2 = 80;

n1 < n2 n1 < n2 // _____// _____

n1 >= n2 n1 >= n2 // _____// _____

(n1 + 35) > n2 (n1 + 35) > n2 // _____// _____

fabs(n1-n2) <= 0.00001fabs(n1-n2) <= 0.00001 // _____// _____

n1 == n2 n1 == n2 // _____// _____

n1 != n2 n1 != n2 // _____// _____

7-14More Logical Expressions More Logical Expressions (with strings this time)(with strings this time)

Examples (Write T for True, or F for False):Examples (Write T for True, or F for False): string s1 = "Pierre";string s1 = "Pierre";

string s2 = "Winder";string s2 = "Winder";

s1 < s2 s1 < s2 // _____// _____

s1 > s2 s1 > s2 // _____// _____

s1 == s2 s1 == s2 // _____// _____

s1 != s2 s1 != s2 // _____// _____

s1 > "Pierrey" s1 > "Pierrey" // _____// _____

s2 < "Windy" s2 < "Windy" // _____// _____

7-15Using relational operators in if Using relational operators in if statementsstatements

double x = 59.0;double x = 59.0; if(x >= 60.0) if(x >= 60.0) {{ cout << "passing";cout << "passing"; }} if(x < 60.0) if(x < 60.0) {{ cout << "below 60.0";cout << "below 60.0"; }}

double x = 59.0; double x = 59.0; ? __________________________ ?? __________________________ ?

double x = 60.0; double x = 60.0; ? __________________________ ?? __________________________ ?

double x = 61.0; double x = 61.0; ? __________________________ ?? __________________________ ?

7-16 Programming Tip: Programming Tip:

Using = for == is a common mistake. For example Using = for == is a common mistake. For example the following two statements are legal, but ...the following two statements are legal, but ...

int x = 25;int x = 25; // Because assignment statements evaluate to the// Because assignment statements evaluate to the // expression on the right of =, x = 1 is always// expression on the right of =, x = 1 is always // 1, which is nonzero, which is true:// 1, which is nonzero, which is true: if(x = 1) if(x = 1) // should be (x == 1)// should be (x == 1) cout << "I'm always displayed";cout << "I'm always displayed";

So consider putting the constant firstSo consider putting the constant first if(1 = x) if(1 = x) // this is an obvious compiletime error// this is an obvious compiletime error

7-177.3 The Alternative Action 7.3 The Alternative Action PatternPattern

Programs often contain statements that select Programs often contain statements that select between one set of actions or anotherbetween one set of actions or another

ExamplesExamples withdraw or deposit moneywithdraw or deposit money pass or fail the entrance requirementspass or fail the entrance requirements

This is the Alternative Action PatternThis is the Alternative Action Pattern choose between two alternate sets of actions choose between two alternate sets of actions

7-18 Alternative ActionAlternative Action

Pattern: Alternative Action

Problem: Must choose one action from two alternatives

Outline: if (true-or-false-condition is true) action-1else action-2

Code if(finalGrade >= 60.0)if(finalGrade >= 60.0) cout << "passing" << endl;cout << "passing" << endl; elseelse cout << "failing" << endl;cout << "failing" << endl;

7-19 if-else General Formif-else General Form

if ( if ( logical-expressionlogical-expression ) ) true-parttrue-part ;; elseelse false-partfalse-part ;;

When the logical expression evaluates to true, the When the logical expression evaluates to true, the true-part executes and the false-part is disregarded. true-part executes and the false-part is disregarded. When the logical expression is false, only the false-When the logical expression is false, only the false-part executes.part executes.

7-20 7.3.1 The if...else statement7.3.1 The if...else statement

The if...else statement allows two alternate The if...else statement allows two alternate courses of action. courses of action.

logicalexpressio

n

False

statement-1

statement-n

statement-1

statement-n

True

FalsePart

TruePart

7-21 if...else Example if...else Example

if(miles > 24000)if(miles > 24000) cout << "Tune-up " << miles-24000 << " miles overdue";cout << "Tune-up " << miles-24000 << " miles overdue";elseelse cout << "Tune-up due in " << 24000-miles << " miles";cout << "Tune-up due in " << 24000-miles << " miles";

MilesMiles OutputOutput

3012330123 ________________________________________________________

20002000 ________________________________________________________

2400024000 ________________________________________________________

Demonstrate the variety of program execution for the three values shown above Demonstrate the variety of program execution for the three values shown above

tuneup.cpptuneup.cpp

7-227.4 The Block with Selection 7.4 The Block with Selection Structures Structures { }{ }

Again, the blocks may be used even when Again, the blocks may be used even when unecessary unecessary and again, consider always using themand again, consider always using them

if(miles > 24000)if(miles > 24000) {{ cout<< "Tune-up " << miles-24000 << " miles overdue";cout<< "Tune-up " << miles-24000 << " miles overdue"; }} elseelse {{ cout<< "Tune-up due in " << 24000-miles << " miles";cout<< "Tune-up due in " << 24000-miles << " miles"; }}

Using curly braces all the time helps avoid Using curly braces all the time helps avoid difficult to detect errorsdifficult to detect errors

7-23 Sometimes blocks are necessarySometimes blocks are necessary

if(GPA >= 3.5)if(GPA >= 3.5)

{ { // true-part contains more than one statement in this block// true-part contains more than one statement in this block

cout << "Congratulations, you're on the Dean's List."<< endl;cout << "Congratulations, you're on the Dean's List."<< endl;

margin = GPA - 3.5;margin = GPA - 3.5;

cout << "You made it by " << margin << " points." << endl;cout << "You made it by " << margin << " points." << endl;

}}

else else

{ { // false-part contains more than one statement in this block// false-part contains more than one statement in this block

cout << "Sorry, you are not on the Dean's List." << endl;cout << "Sorry, you are not on the Dean's List." << endl;

margin = 3.5 - GPA;margin = 3.5 - GPA;

cout << "You missed it by " << margin << " points." << endl;cout << "You missed it by " << margin << " points." << endl;

}}

totalMargin = totalMargin + margin;totalMargin = totalMargin + margin;

7-247.4.1 the trouble in Forgetting 7.4.1 the trouble in Forgetting { }{ }

Failing to use { and }Failing to use { and } if(GPA >= 3.5) if(GPA >= 3.5) // The true-part is the first cout only// The true-part is the first cout only cout <<"Congrats, you're on the Dean's List. ";cout <<"Congrats, you're on the Dean's List. "; margin = GPA - 3.5;margin = GPA - 3.5; cout <<"You made it by " << margin << " points.";cout <<"You made it by " << margin << " points.";

else else <<<< Error >>>><<<< Error >>>>

7-257.4.1 the trouble in Forgetting 7.4.1 the trouble in Forgetting { }{ }

There are no compiletime errors next, but there is There are no compiletime errors next, but there is an intent error. an intent error.

elseelse cout << "Sorry, you're not on the Dean's List." << endl;cout << "Sorry, you're not on the Dean's List." << endl; margin = 3.5 - GPAmargin = 3.5 - GPA ;; cout << "You missed it by " << margin << " points.";cout << "You missed it by " << margin << " points.";

With the above false part, you could get this With the above false part, you could get this confusing output (when GPA = 3.9):confusing output (when GPA = 3.9):

Congrats, you're on the Dean's list.Congrats, you're on the Dean's list. You made it by 0.4 points.You made it by 0.4 points. You missed it by -0.4 points.You missed it by -0.4 points.

7-26 7.5 bool Objects7.5 bool Objects

The standardThe standard bool bool class stores one of two class stores one of two valuesvalues

true true and and falsefalse

A A boolbool object stores the result of a logical object stores the result of a logical expression:expression:

bool ready = false;bool ready = false; double hours = 4.5;double hours = 4.5; ready = hours >= 4.0;ready = hours >= 4.0; cout << ready << endl; cout << ready << endl; // Displays 1 for true// Displays 1 for true

7-27 bool Functionsbool Functions

It is common to have functions that return one It is common to have functions that return one of the bool values (true or false).of the bool values (true or false).

bool odd(int n) bool odd(int n) { { // post: return true if n is an odd integer// post: return true if n is an odd integer return (n % 2) != 0;return (n % 2) != 0;}}

// Client code// Client codeif( odd(j) )if( odd(j) ) j = j + 1; j = j + 1; // assert: j is an even integer// assert: j is an even integer

7-28 7.5.1 Boolean Operators 7.5.1 Boolean Operators

A logical operator (&& means AND) used in A logical operator (&& means AND) used in an if...else statement:an if...else statement:

if( (test >= 0) && (test <= 100) )if( (test >= 0) && (test <= 100) ) cout << "Test in range";cout << "Test in range"; elseelse cout << "**Warning--Test out of range"; cout << "**Warning--Test out of range";

The code describes whether or not test is in The code describes whether or not test is in the range of 0 through 100 inclusive.the range of 0 through 100 inclusive.

7-29Truth Tables for Boolean Truth Tables for Boolean OperatorsOperators

Truth tables for the Logical (Boolean) Truth tables for the Logical (Boolean) operators !, ¦¦, && operators !, ¦¦, &&

! (not) ¦¦ (or) && (and)Expression Result Expression Result Expression Result! false! true

truefalse

true ¦¦ truetrue ¦¦ falsefalse ¦¦ truefalse ¦¦ false

truetruetruefalse

true && truetrue && falsefalse && truefalse && false

truefalsefalsefalse

7-30 Using && in an expressionUsing && in an expression

Assuming test == 97, Assuming test == 97, Is test within the range of 0 and 100 inclusive?Is test within the range of 0 and 100 inclusive?

( (test >= 0) && (test <= 100) ) ( (test >= 0) && (test <= 100) ) ( ( 97 >= 0) && ( 97 <= 100) ) ( ( 97 >= 0) && ( 97 <= 100) ) ( true && true )( true && true ) truetrue

Is test outside the range of 0 and 100 inclusive?Is test outside the range of 0 and 100 inclusive? ( (test < 0) ¦¦ (test > 100) ) ( (test < 0) ¦¦ (test > 100) ) ( ( 97 < 0) ¦¦ ( 97 > 100) ) ( ( 97 < 0) ¦¦ ( 97 > 100) ) ( false ¦¦ false )( false ¦¦ false ) false false

Evaluate both expressions when test == 101 ?__?Evaluate both expressions when test == 101 ?__?

7-31 More Precedence RulesMore Precedence Rules

The following slide summarizes all operators used in The following slide summarizes all operators used in this textbook (we've seen 'em all)this textbook (we've seen 'em all)

Precedence: most operators are evaluated (grouped) in a Precedence: most operators are evaluated (grouped) in a left-to-right order:left-to-right order:

a / b / c / da / b / c / d is equivalent tois equivalent to (((a/b)/c)/d)(((a/b)/c)/d)

Assignment operators group in a right-to-left order so the Assignment operators group in a right-to-left order so the expression expression

x = y = z = 0.0 x = y = z = 0.0 is equivalent tois equivalent to (x=(y=(z=0.0))) (x=(y=(z=0.0)))

Also note that standard C++ has the operators:Also note that standard C++ has the operators:not and or not and or // we'll use ! && ||// we'll use ! && ||

7-32 Operators used in this bookOperators used in this book

7-33Applying Operators and Applying Operators and Precedence RulesPrecedence Rules

Use the precedence rules to evaluate the Use the precedence rules to evaluate the following expression:following expression:

int j = 5; int j = 5; int k = 10;int k = 10;bool TorF;bool TorF;

TorF = (j * (1 + k) > 55) ¦¦ (j + 5 <= k) && (j>k) TorF = (j * (1 + k) > 55) ¦¦ (j + 5 <= k) && (j>k)

What is assigned to What is assigned to TorFTorF_______?_______?

7-347.5.3 The Boolean "or" 7.5.3 The Boolean "or" |||| with with a grid Objecta grid Object

bool moverOnEdge(const grid & g)bool moverOnEdge(const grid & g){ { // post: return true if the mover is on an edge// post: return true if the mover is on an edge // or false otherwise// or false otherwise return( g.row()==0 return( g.row()==0 // on north edge?// on north edge? || g.row()==g.nRows()-1 || g.row()==g.nRows()-1 // on south edge?// on south edge? || g.column()==0 || g.column()==0 // on west edge?// on west edge? || g.column()==g.nColumns()-1 ); || g.column()==g.nColumns()-1 ); // east?// east?}}

int main()int main(){{ grid tarpit( 5, 10, 4, 4, east );grid tarpit( 5, 10, 4, 4, east ); if( moverOnEdge(tarpit) )if( moverOnEdge(tarpit) ) cout << "On edge" << endl;cout << "On edge" << endl; elseelse cout << "Not" << endl;cout << "Not" << endl; return 0;return 0;}}

Optional Demo: onedge.cpp

7-357.5.4 Short Circuit Boolean 7.5.4 Short Circuit Boolean EvaluationEvaluation

C++ logical expressions evaluate subexpressions C++ logical expressions evaluate subexpressions in a left to right orderin a left to right order

Sometimes the evaluation can stop earlySometimes the evaluation can stop early This never evaluates This never evaluates sqrtsqrt of a negative number: of a negative number:

if((x >= 0.0) && (sqrt(x) <= 2.5))if((x >= 0.0) && (sqrt(x) <= 2.5)) // ... // ...

test>100 test>100 is not evaluated whenis not evaluated when test<0 test<0 is trueis true if(test < 0 || test > 100)if(test < 0 || test > 100) // ...// ...

7-36 7.6 A bool member function7.6 A bool member functionPREREQUISITE: Chapter 6PREREQUISITE: Chapter 6

Consider changing bankAccount::withdraw so it Consider changing bankAccount::withdraw so it only withdraw money if the balance is sufficient. only withdraw money if the balance is sufficient.

Also have it return true in this caseAlso have it return true in this case Have it return false when there are insufficient fundsHave it return false when there are insufficient funds

First change heading in class bankAccount First change heading in class bankAccount bool withdraw(double withdrawalAmount);bool withdraw(double withdrawalAmount); // was void// was void

7-37 a bool member function a bool member function continuedcontinued

Also change implementation in baccount.cppAlso change implementation in baccount.cpp

bool bankAccount::withdraw(double withdrawalAmount)bool bankAccount::withdraw(double withdrawalAmount) {{ // post: return true if withdrawal was successful // post: return true if withdrawal was successful // or false with insufficient funds// or false with insufficient funds bool result = false;bool result = false;

if(my_balance >= withdrawalAmount)if(my_balance >= withdrawalAmount) {{ my_balance = my_balance - withdrawalAmount;my_balance = my_balance - withdrawalAmount; result = true;result = true; }} return result;return result; }}

7-38 7.7 Multiple Selection7.7 Multiple Selection

Nested logic: Nested logic: one control structure contains another similar control one control structure contains another similar control

structurestructure an if...else inside another if...elsean if...else inside another if...else allows selections from 3 or more alternativesallows selections from 3 or more alternatives

We must often select one alternative from manyWe must often select one alternative from many

7-39

7-40 Example of Multiple Selection Example of Multiple Selection nested if...elsenested if...else

if(GPA < 3.5)if(GPA < 3.5) cout << "Try harder" << endl;cout << "Try harder" << endl; elseelse if(GPA < 4.0)if(GPA < 4.0) cout << "Dean's List" << endl;cout << "Dean's List" << endl; elseelse cout << "President's list" << endl;cout << "President's list" << endl;

GPAGPA Output:Output:

3.03.0 ____________________________________

3.63.6 ____________________________________

4.04.0 ____________________________________

The false part is another if...else

7-41 Active LearningActive Learning

Given the scale below, Complete the function Given the scale below, Complete the function (next slide) with a nested if..else to display the (next slide) with a nested if..else to display the appropriate message:appropriate message:

Value of C°Value of C° OutputOutput

C >= 34 C >= 34 HotHot

20 <= C < 34 20 <= C < 34 WarmWarm

12 <= C < 20 12 <= C < 20 MildMild

0 <= C < 12 0 <= C < 12 ColdCold

C < 0C < 0 FreezingFreezing

7-42

string weather(int C)string weather(int C){ { // post: return appropriate message// post: return appropriate message string result;string result; if( C >= 34 )if( C >= 34 ) result = "Hot";result = "Hot"; else if(C >= 20)else if(C >= 20) result ="Warm";result ="Warm";

return result;return result;}}

7-43 7.7.2 Multiple Returns7.7.2 Multiple Returns

It's possible to have multiple return statements in It's possible to have multiple return statements in a function a function terminate when the first return executesterminate when the first return executes

string letterGrade(double percentage)string letterGrade(double percentage) { { if(percentage >= 90)if(percentage >= 90) return "A";return "A"; if(percentage >= 80) if(percentage >= 80) return "B";return "B"; if(percentage >= 70) if(percentage >= 70) return "C";return "C"; if(percentage >= 60) if(percentage >= 60) return "D";return "D"; return "F"; return "F"; // return F when percentage < 0// return F when percentage < 0 }}

7-44 7.8 Testing Multiple Selection7.8 Testing Multiple Selection

It is often difficult and unnecessary to test It is often difficult and unnecessary to test every possible value every possible value imagine all those doubles 0.1, imagine all those doubles 0.1, 0.001, 0.0001,...0.001, 0.0001,...

Testing our code in "most" branches can Testing our code in "most" branches can prove dangerously inadequateprove dangerously inadequate

Each branch through the multiple selection Each branch through the multiple selection should be tested.should be tested.

7-45 Perform Branch Coverage TestPerform Branch Coverage Test

To correctly perform branch coverage testing To correctly perform branch coverage testing we need to do the following: we need to do the following:

Establish a set of data that ensures all paths will Establish a set of data that ensures all paths will execute execute the statements after the logical expressionsthe statements after the logical expressions

Execute the code Execute the code call the functioncall the function with the nested logic with the nested logic for all selected data values for all selected data values

Observe that the code behaves correctly for Observe that the code behaves correctly for all all data data

compare program output with expected resultscompare program output with expected results

This is glass box testing This is glass box testing whenwhen you look at the codeyou look at the code

7-46 7.8.1 Boundary Testing7.8.1 Boundary Testing

Boundary testing involves executing the code Boundary testing involves executing the code using the boundary (cutoff) valuesusing the boundary (cutoff) values

What grade would you receive with a percentage What grade would you receive with a percentage of 90 using this codeof 90 using this code

if( percentage > 90 )if( percentage > 90 ) grade = "A";grade = "A"; else if( percentage >= 80 )else if( percentage >= 80 ) grade = "B";grade = "B";

Optional DemoOptional Demo b&btest.cpp b&btest.cpp Perform branch and boundary testing with the temperature example Perform branch and boundary testing with the temperature example

7-477.9 The switch Statement 7.9 The switch Statement (General form)(General form)

switch ( switch ( switch-expression switch-expression )) {{ casecase value-1value-1 ::

statement(s)-1statement(s)-1

break ;break ; ... // many cases are allowed... // many cases are allowed

casecase value-nvalue-n ::

statement(s)-nstatement(s)-n

break ;break ;

default :default : default-statement(s) default-statement(s) }}

7-48 Switch controlSwitch control

When a switch statement is encountered:When a switch statement is encountered: the switch-expression is evaluated. This value is the switch-expression is evaluated. This value is

compared to each case value until switch-expression compared to each case value until switch-expression == case value. All statements after the colon : are == case value. All statements after the colon : are executed. executed.

It is important to include the break statementIt is important to include the break statement The switch expression must evaluate to one of C+The switch expression must evaluate to one of C+

+'s integral types+'s integral types int, char, or enumint, char, or enum

7-49 7.9.1 char Objects7.9.1 char Objects

A char object stores 1 characterA char object stores 1 character'A' 'x' 'c' '?' ' ' '1' '.''A' 'x' 'c' '?' ' ' '1' '.'

or 1 escape sequenceor 1 escape sequence

7-50 Example switch statement:Example switch statement:

char option = '?';char option = '?';cout << "Enter W)ithdraw D)eposit B)alances: ";cout << "Enter W)ithdraw D)eposit B)alances: ";cin >> option;cin >> option;switch(option) {switch(option) { case 'W':case 'W': cout << "Withdraw" << endl;cout << "Withdraw" << endl; break;break; case 'D':case 'D': cout << "Deposit" << endl;cout << "Deposit" << endl; break;break; case 'B':case 'B': cout << "Balance" << endl;cout << "Balance" << endl; break;break; default: default: cout << "Invalid" << endl;cout << "Invalid" << endl;} } // end switch// end switch

7-51 Trace the previous switchTrace the previous switch

Show output when Show output when

option == '?'option == '?' ____________?____________?

option == 'W'option == 'W' ____________?____________?

option == 'B'option == 'B' ____________?____________?

option == 'A'option == 'A' ____________?____________?

option == 'Q'option == 'Q' ____________?____________?

top related