August 2012
Intermediate to advanced
976 pages
30h 17m
English
switch StatementA 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 ...
Read now
Unlock full access