Switch (Multiple Conditions)

switch is a function that handles multiple conditions and gives a different response to each condition. It is a very complex type of conditional.

Switch

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:

Do you prefer jazz, classical, or pop music?

We could give four different responses to the viewer’s answer:

  1. Jazz involves improvisation.
  2. Classical music has a long history.
  3. Pop cds sell very well.
  4. (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:

switch(variable)

case ‘answer1’:
printf(“\nResponse 1.”);
break;
case ‘answer2’:
printf(“\nResponse 2.”);
break;
case ‘answer3’:
printf(“\nResponse 3.”);
break;
default:
printf(“\nDefault response.”);
break;

}

Now let’s plug in our music question and responses, to create this program:

#include<stdio.h>
void main( )
{
char music;
printf(“\nDo you prefer jazz (type j), classical (type c), or pop (type p)? “);
scanf(” %c”, &music);
switch(music)

case ‘j’:
printf(“\nJazz involves improvisation.”);
break;
case ‘c’:
printf(“\nClassical music has a long history.”);
break;
case ‘p’:
printf(“\nPop cds sell very well.”);
break;
default:
printf(“\nThat is an interesting type of music.”);
break;

}
}

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.

Published by Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Join the Conversation

2 Comments

Leave a comment

Your email address will not be published. Required fields are marked *