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.
switch (integer expression)
case constant 1:
case constant 2:
case constant 3:
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,
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.
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
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.
It is a keyword that can’t be changed and is executed if none of the cases has matched.