We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 8
202
Chapter 4 Making Decisions
—
4.26 What will the following program display
4.25 The following statements use conditional expressions. Rewrite each with an if/
else statement.
A) j= k> 907 572 12;
B) factor = x >= 102 y #22: y* 35;
C) total ++ count == 1? sales : count * sales;
D) cout << (((num # 2) == 0) 2 Oda\.nn) 5
Even\a"
Hinclude
using namespace std;
int main()
4
const int UPPER = 8, LOWER = 2;
int numl, num, numd = 12, num
nunl = nun < nun ? UPPER
nun2 = numi > UPPER ? numd
cout << numl <<
return 0;
LOWER;
LOWER;
<< numa << endl;
414) The switch Statement
= CONCEPT: The switch statement lets the value of a variable or expression
determine where the program will branch.
A branch occurs when one part of a program causes another part to execute. ‘The if/else
if statement allows your program to branch into one of several possible paths. It per
forms a series of tests (usually relational) and branches when one of these tests is true. The
‘switeh statement is a similar mechanism, It, however, tests the value of an integer expres-
sion and then uses that value to determine which set of statements to branch to, Here is
the format of the switeh statement:
switch (IntegerExpression)
«
case ConstantExpressiom
// place one or more
// statements here
case Constantéxpression:
// place one or more
// statenents here
// case statements may be repeated as many
// times as necessary
default:
// place one or more
// statenents here@
9
4.14 The switch Statement
The first line of the statement starts with the word switch, followed by an integer expres-
sion inside parentheses. This can be either of the following
a variable of any of the integer data types (including char)
‘+ an expression whose value is of any of the integer data types
‘On the next line is the beginning of a block containing several case statements. Each case
statement is formatted in the following manner:
case Constant Expression
// place one or nore
// statements here
After the word case is a constant expression (which must be of an integer type), followed
by a colon, The constant expression may be an integer literal or an integer named con-
stant, The case statement marks the beginning of a section of statements. ‘The program
branches to these statements if the value of the switch expression matches that of the
case expression.
WARNING! The expression of each case statement in the block must be unique.
NOTE: The expression following the word case must be an integer literal or constant. It
cannot be a variable, and it cannot be an expression such as x < 22 orn == 50.
‘An optional default section comes after all the case statements. The program branches
to this section if none of the case expressions match the switch expression. So, it func
tions like a trailing else in an it/eise if statement.
Program 4-23 shows how a simple switch statement works.
Program 4-23
“
“
Hing
int
‘The switch statement in this program tells the user something
he or she already knows: the data just entered
elude
ng namespace std;
main()
char choice;
cout << "Enter A B, or Cr
cin >> choice;
switch (choice)
4
case 'N: cout << "You entered A.\n";
break;
case ‘BY: cout << "You entered B.\n";
break;
case 'C': cout << “You entered C.\n";
break;
default: cout << “You did not enter A, B, or Cl\n";
>
return 0;
(program continues)
203204
Chapter 4 Making Decisions
Program 4-23 (continued)
Program Output with Example Input Shown in Bold
Enter &, 8, or C: B [Enter]
You entered B.
Program Output with Example Input Shown in Bold
Enter A By or C: F [Enter]
You did not enter a B, or Cl
The first case statement is case * a’ :, the second is case‘ B':, and the third is case
‘crs. These statements mark where the program is to branch to if the variable choice
contains the values * a ,* B', or* c’ . (Remember, character variables and literals are con-
sidered integers.) The default section is branched to if the user enters anything other
than A, B, or C.
Notice the break statements that are in the case' A, case’ 3, and case'C’ sections.
switch (choice)
4
case 'N:cout << "You entered A.\n";
break; <———
case 'B: cout << "You entered B.\n";
break; =———
case 'C':cout << "You entered C.\n";
break; <————
default: cout << "You did not enter A B, or CI\n!
>
‘The case statements show the program where to start executing in the block and the break
statements show the program where to stop. Without the break statements, the program.
would execute all of the lines from the matching case statement to the end of the block.
og NOTE: The default section (or the last case section, if there is no defauit) does not
need a break statement. Some programmers prefer to put one there anyway, for
consistency.
Program 4-24 is a modification of Program 4-23, without the break statements.
Program 4.24
// The switch statement in this program tells the user something
// be or she already knows: the data just entered!
Hinelude
using namespace std;
int main()
chaz choice;4.14 The switch Statement
) cout << "Enter AB, or C: "3
1 ein >> choice;
// The following switch is
3 // missing its break statements!
24 switch (choice)
‘
case ‘A: cout << "You entered A\\
case 'B': cout << "You entered B.\
case 'C': cout << "You entered C.\
19 default: cout << “You did not enter A, B, or Cl\n";
a)
ai return 0;
Program Output with Example Input Shown in Bold
Enter Ay B, or C: AlEnter]
You entered A
You entered B.
You entered c.
You did not enter a B, or Ci
Program Output with Example Input Shown in Bold
Enter A 8, or C: [Enter]
You entered c.
You did not enter A B, or Cl
Without the break statement, the program “falls through” all of the statements below the
one with the matching case expression. Sometimes this is what you want. Program 4-25
lists the features of three TV models a customer may choose from. The Model 100 has
remote control. The Model 200 has remote control and stereo sound. The Model 300 has
remote control, stereo sound, and picture-in-a-picture capability. ‘The program uses a
switch statement with carefully omitted breaks to print the features of the selected model,
Program 4.25
1 // this program is carefully constructed to use the "fall through"
// feature of the switch statement.
5 Hinelude
| using namespace std;
int main()
5 int medelNum; // Model number
) // Get a model number from the
21 cout << "Our Tvs come in three
2 cout << "The 100, 200, and 300. Which do you want?
5 ein >> model wuny
(program continues)
205206
Chapter 4 Making Decisions
Program 4-25 (continued)
// Display the model's features.
cout << "That model has the following feature:
switch (model Num
‘
case 300: cout << "\tPicture-in-a-picture. \n";
case 200: cout << “\tStereo sound. \n";
case 100: cout << “\tRemote con :
break;
default: cout << "You can only choose the 100,
cout << "200, or 300. \n";
>
return 0;
»
Program Output with Example Input Shown in Bold
Our TVs cone in three models:
The 100, 200, and 300. Which do you want? 100 [Enter]
That model has the following features:
Remote control.
Program Output with Example Input Shown in Bold
Our TVs cone in three models:
The 100, 200, and 300. Which do you want? 200 [Enter]
That model has the following feature
Stereo sound.
Remote control.
Program Output with Example Input Shown in Bold
Our TVs cone in three models:
The 100, 200, and 300. Which do you want? 300 [Enter]
That model has the following feature
Picture-in-a-picture.
Stereo sound.
Remote control.
Program Output with Example Input Shown in Bold
Our TVs cone in three model
The 100, 200, and 300. Which do you want? 500 [Enter]
That model has the following feature
You can only choose the 100, 200, or 300.
Another example of how useful this “fall through” capability can be is when you want the
program to branch to the same set of statements for multiple case expressions. For
instance, Program 4-26 asks the user to select a grade of pet food. The available choices
are A,B, and C. The switch statement will recognize either upper or lowercase letters.
Program 4.26
// The switch statement
in this program uses the "fall through”
// feature to catch both uppercase and lowercase letters entered
// by the user.
#include
using namespace std;4.14 The switch Statement 207
int main()
a ¢
> char feedGrade;
10
11 // Get the desired grade of feed.
12 cout << "Our pet food is available in three grades: \n";
1) cout << "A, B, and C. Which do you want pricing for? ";
1) cin >> feedcrade;
o
16 // Display the price.
17 switeh( feedGrade)
as
19 case ‘a’
20 case 'N': cout << "30 cents per pound. \n"
21 break;
22 case 'b’
3 case 'B': cout << "20 cents per pound. \n"
break;
case 'C': cout << "15 cents per pound. \n"
7 break;
28 default: cout << "That is an invalid choice. \n";
2}
) return 0;
ay
Program Output with Example Input Shown in Bold
our pet food is available in three grades:
a, B, and C. Which do you want pricing for? b [Enter]
20 cents per pound.
Program Output with Example Input Shown in Bold
our pet food is available in three grades:
A, B, and C. Which do you want pricing for? B [Enter]
20 cents per pound.
When the user enters’ a’ the corresponding ease has no statements associated with it, so
the program falls through to the next case, which corresponds with.
case "Ni cout << "30 cents per pound. \n";
break:
The same technique is used for‘ b* and".
Using switch in Menu Systems
The switch statement is a natural mechanism for building menu systems. Recall that
Program 4-18 gives a menu to select which health club package the user wishes to pur
chase. The program uses if/else if statements to determine which package the user has
selected and displays the calculated charges. Program 4-27 is a modification of that pro-
‘gram, using a switch statement instead of if/else if.208 — Chapter 4 Making Decisions
Program 4.27
1 // This program uses a switch statenent to determine
2 // the item selected from a menu.
3 finclude
4 #include
5 using namespace std;
int main()
at
2 int choice; // To hold a menu choice
) int months; // To hold the number of months
1 double charges; // To hold the monthly charges
5 // Constants for membership rates
const double ADULT = 40.0,
CHILD = 20.0,
SENIOR = 30.0;
// constants for menu choices
29 const int ADULT_CHOICE = 1,
0 CHILD_CHOICE = 2,
a SENIOR CHOICE = 3,
22 urT_cHorce = 4;
24 // Display the menu and get a choice.
5 cout << "\t\tiealth Club Membership Menu\n\n"
<< "1. Standard Adult Membership\n’
2 << "2. Child Membership\n"
<< "3, Senior Citizen Menbership\n'
29 <<"d. Quit the Program\n\n"
0 << "Enter your choice: ";
1 cin >> choice;
J/ Set the nuneric output formatting.
1 cout << fixed << showpoint << setprecision( 2);
5 // Respond to the user's menu selection.
switch (choice)
4
case ADULT_CHOICE:
40 cout << "For how many months? ";
a1 cin >> months;
42 charges = months * ADULT;
4 cout << "The total charges are charges << endl;
4 break;
16 case CHILD_CHOICE:
a cout << "For how many months? ";
4 cin >> months;
a charges = months * CBILD;
0 cout << "The total charges are
51 break;
<< charges << endl;4.14 The switch Statement 209
53 case SENIOR_CHOICE:
34 cout << “For how many months? ";
35 cin >> months;
56 charges = months * SENIOR;
87 cout << "The total charges are $" << charges << endl;
58 break;
59
60 case QUIT_CHOICE:
61 cout << "Program ending. \n";
62 break;
63
64 default:
65 cout << "The valid choices are 1 through 4. Rua the\a"
66 << "program again and select one of those. \n";
oy
63
69 return 0;
yoy
@& Checkpoint
Mmyprogramminglab www.myprogramminglab.com
4.27 Explain why you cannot convert the following i#/else if statement into a
switch statement,
Lf (temp == 100)
x= 0;
else if (population > 1000)
xe ap
else if (rate <.1)
xe
4.28 What is wrong with the following switen statement?
switch (temp)
4
case temp <0: cout << "Temp is negative. \n";
break;
case temp == 0: cout << "Temp is zero.\n";
break;
case temp > 0: cout << "Temp is positive. \n";
break;