Sams Teach Yourself C in 21 Days

(singke) #1
Enter 1 for task A.
Enter 2 for task B.
Enter 3 for task C.
Enter 4 for task D.
Enter 5 to exit program.
1

Executing task A.
Enter 1 for task A.
Enter 2 for task B.
Enter 3 for task C.
Enter 4 for task D.
Enter 5 to exit program.
6

Invalid choice, try again.
Enter 1 for task A.
Enter 2 for task B.
Enter 3 for task C.
Enter 4 for task D.
Enter 5 to exit program.
5

Exiting program now...
This program has one has a switch statement that has cases based on the choices
of a menu that is displayed. Line 14 calls the menu the first time and gets a com-
mand value from it. If the value is anything other than 5 ,a whileloop is executed. This
while loop is primarily a switch statement that executes different code based on the com-
mand selected from the menu. Once the appropriate case is executed, the menu is redis-
played and a new command is obtained in line 55.
Having execution “fall through” parts of a switchconstruction can be useful at times.
Say, for example, that you want the same block of statements executed if one of several
values is encountered. Simply omit the breakstatements and list all the casetemplates
before the statements. If the test expression matches any of the caseconditions, execu-
tion will “fall through” the following casestatements until it reaches the block of code
you want executed. This is illustrated in Listing 13.8.

LISTING13.8 fallthru.c. Another way to use the switchstatement
1: /* Another use of the switch statement. */
2:
3: #include <stdio.h>
4: #include <stdlib.h>

326 Day 13

INPUT/
OUTPUT

ANALYSIS

21 448201x-CH13 8/13/02 11:12 AM Page 326

Free download pdf