Lesson 7- Switch Case

We often face situations where we have to choose from several given choices. For example, which college to go to or which park to visit. In such cases, we use a series of if-clauses but C language provides a more structured approach. The case-control structure can be used in situations where you have to choose from several options.

Syntax:

switch (integer expression)

{

case constant 1:

 Do this;

 break;

case constant 2:

 Do this;

 break;

case constant 3:

Do this;

break;

default:

 Do this;

}

Keywords:

  • switch
  • case
  • default

Integer expression:

Here you can write the variable on which decision will depend. For example, if earlier in the same code user is asked to input any number from the range 10-13, and that number is stored in a variable “num”. If the output needs to be decided on the value of num. Then you must write. switch (num)

case constant 1:

Here the case is the keyword that can not be changed. Constant 1 will be changed according to the program requirements. For example, in our case, the output depends on the value of variable “num”. According to our program, the possible values that the user can input are 10,11,12 or 13.

So here we can write,

case 10:

case 11:

case 12:

case 13:

Do this:

This represents the block of statements, that you want to execute if the particular case has been matched. For example, you can add any printf() function to print in each case.

Like,

printf (“you have entered 10”);

printf (“you have entered 11”);

printf (“you have entered 12”);

printf (“you have entered 13”);

printf (“invalid input”); —> in case of default

break:

This is a library function that can’t be changed. It is used to come out of the case structure if a particular case has matched. So the rest of the cases are skipped.

default:

It is a keyword that can’t be changed and is executed if none of the cases has matched.