|
C++
Tutorial - Lesson 6: Conditional Processing, Part 2 |
 |
Switch Statements and Logical
Operators |
 |
|
|
 |
by John
Kopp
Welcome to About.com's C++ tutorial. This second lesson on
conditional processing introduces both the switch statement and logical operators. The switch
statement is a construct that is used to replace deeply nested
or chained if/else statements. Nested if/else statements arise
when there are multiple alternative threads of execution based
on some condition. Here's an example. Suppose that an ice
cream store has asked us to write a program that will automate
the taking of orders. We will need to present a menu and then
based on the customer's choice take an appropriate action.
#include <iostream> using namespace
std;
int
main() { int
choice;
cout <<
"What flavor ice cream do want?" <<
endl; cout << "Enter 1
for chocolate" <<
endl; cout << "Enter 2
for vanilla" <<
endl; cout << "Enter 3
for strawberry" <<
endl; cout << "Enter 4
for green tea flavor, yuck" <<
endl; cout << "Enter
you choice: ";
cin
>> choice;
if (choice ==
1)
{ cout
<< "Chocolate, good choice" <<
endl; } else
if (choice == 2)
{ cout
<< "Vanillarific" <<
endl; } else
if (choice == 3)
{ cout
<< "Berry Good" <<
endl; } else
if (choice == 4)
{ cout
<< "Big Mistake" <<
endl; } else
{ cout
<< "We don't have any" <<
endl; cout
<< "Make another selection" <<
endl; }
return
0; } |
This program will work fine, but the if/else block is
cumbersome. It would be easy, particularly if there were more
choices and maybe sub choices involving more if/else's to end
up with program that doesn't perform the actions intended.
Here's the same program with a switch.
#include <iostream> using namespace
std;
int
main() { int
choice;
cout <<
"What flavor ice cream do want?" <<
endl; cout << "Enter 1
for chocolate" <<
endl; cout << "Enter 2
for vanilla" <<
endl; cout << "Enter 3
for strawberry" <<
endl; cout << "Enter 4
for green tea flavor, yuck" <<
endl; cout << "Enter
you choice: ";
cin
>> choice;
switch
(choice) { case
1: cout
<< "Chocolate, good choice" <<
endl; break; case
2: cout
<< "Vanillarific" <<
endl; break; case
3: cout
<< "Berry Good" <<
endl; break; case
4: cout
<< "Big Mistake" <<
endl; break; default: cout
<< "We don't have any" <<
endl; cout
<< "Make another selection" <<
endl; }
return
0; } |
Next page > Page
2 of Tutorial > Page 1,
2,
3
|
|
|