Switch (Multiple Conditions)
A switch is a function that handles multiple conditions and gives a different response to each condition. It is a very complex type of conditional.
If you ask a question that could have several different answers, and you want to give a different response to each answer, then you must use a switch.
Here is an example of this type of question:
We could give four different responses to the viewer’s answer:
- Jazz involves improvisation.
- Classical music has a long history.
- Pop cds sell very well.
- (for all other answers) That is an interesting type of music.
The switch has several parts. Each of the preferences (jazz, classical, pop) is called a case. The fourth answer will simply default to the general response.
After each case we must break, which exits the switch. This happens when the viewer types one of the correct answers (jazz, classical, or pop). At the end we use the default.
Here is a general format for writing switches:
Now let’s plug in our music question and responses, to create this program:
void main( )
printf(“\nDo you prefer jazz (type j), classical (type c), or pop (type p)? “);
scanf(” %c”, &music);
Type this source code in your editor and save it as music.c then compile it, link it, and run it.
Continue on to While Loops.