The switch Statement
A new stmt for controlling multiple
branches
Uses controlling expression which returns
bool data type (true or false)
Syntax:
Display page 62 next slide
Copyright © 2002 Pearson Education, Inc. Slide 23
switch Statement Syntax
Display, page 62
Copyright © 2002 Pearson Education, Inc. Slide 24
The switch Statement in Action
Display,
page 62
Copyright © 2002 Pearson Education, Inc. Slide 25
The switch: multiple case labels
Execution ‘falls thru’ until break
switch provides a ‘point of entry’
Example:
case ‘A’:
case ‘a’:
cout << “Excellent: you got an ‘A’!\n”;
break;
case ‘B’:
case ‘b’:
cout << “Good: you got a ‘B’!\n”;
break;
Note multiple labels provide same ‘entry’
Copyright © 2002 Pearson Education, Inc. Slide 26
switch Pitfalls/Tip
Forgetting the break;
No compiler error
Execution simply ‘falls thru’ other cases until
break;
Biggest use: MENUs
Provides clearer ‘big-picture’ view
Shows menu structure effectively
Each branch is one menu choice
Copyright © 2002 Pearson Education, Inc. Slide 27
switch Menu Example
Switch stmt ‘perfect’ for menus:
switch (response)
{
case ‘1’:
// Execute menu option 1
break;
case ‘2’:
// Execute menu option 2
break;
case 3’:
// Execute menu option 3
break;
default:
cout << “Please enter valid response.”;
}
Copyright © 2002 Pearson Education, Inc. Slide 28
switch Example
Write a program that will input 2 integers with
One of the common four mathematical operations
(+, - , *, /) in between, then print the result of the
operation using switch statement.
Copyright © 2002 Pearson Education, Inc. Slide 29