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 ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.