0
3.9kviews
Explain switch control statement with the help of example.
1 Answer
1
210views
  • Decision making are needed when, the program encounters the situation to choose a particular statement among many statements.

  • If a programmer has to choose one block of statement among many alternatives, nested if...else can be used but, this makes programming logic complex.

  • This type of problem can be handled in C programming using switch statement.

  • A switch statement allows a variable to be tested for equality against a list of values.

  • Each value is called a case, and the variable being switched on is checked for

  • each switch case.

Syntax:

switch(expression) {
case constant-expression  :
statement(s);
break; /* optional */

case constant-expression  :
statement(s);
break; /* optional */

    /* you can have any number of case statements */
default : /* Optional */
statement(s);
}

Example:

#include <stdio.h>
int main (){
char grade = 'B';

switch(grade)   {
    Case 1:
printf("Excellent!\n" );
break;

Case 2:
printf("Well done\n" );
break;
    Case 3:
printf("You passed\n" );
break;
    Case 4:
printf("Better try again\n" );
break;
Default :
printf("Invalid grade\n" );
    }
printf("Your grade is  %c\n", grade );
return 0;
}
Please log in to add an answer.