0% found this document useful (0 votes)
2 views

switch statement control structure

The document discusses the switch statement, a control structure for managing multiple branches in programming. It outlines the syntax, execution flow, and common pitfalls, such as forgetting to include a break statement. Additionally, it highlights the switch statement's effectiveness for menu-driven programs and provides an example for implementing basic mathematical operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

switch statement control structure

The document discusses the switch statement, a control structure for managing multiple branches in programming. It outlines the syntax, execution flow, and common pitfalls, such as forgetting to include a break statement. Additionally, it highlights the switch statement's effectiveness for menu-driven programs and provides an example for implementing basic mathematical operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

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

You might also like