O'Reilly logo

C++ Primer, Fifth Edition by Barbara E. Moo, Josée Lajoie, Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.3.2. The switch Statement

A switch statement provides a convenient way of selecting among a (possibly large) number of fixed alternatives. As one example, suppose that we want to count how often each of the five vowels appears in some segment of text. Our program logic is as follows:

• Read every character in the input.

• Compare each character to the set of vowels.

• If the character matches one of the vowels, add 1 to that vowel’s count.

• Display the results.

For example, when we run the program on the text of this chapter, the output is

Number of vowel a: 3195Number of vowel e: 6230Number of vowel i: 3102Number of vowel o: 3289Number of vowel u: 1033

We can solve our problem most directly using a switch statement:

// initialize counters ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required