• Switch statement is an alternative to if else ladder statement which allows us to execute multiple operations for different values.
  • We can define various statement in multiple cases for different values of single variable.

Rules for switch statement

  • Switch expression should be an integer or character data type.
  • Case value must be an integer or constant value.
  • We can use only case value inside the switch statement.
  • Break statement is not mandatory in switch. It is optional.
  • If a program does not find a break statement in switch expression, all the cases in the switch will be executed along with the matched case.

Syntax for switch statement

switch(expression){    
case value1:    
//code to be executed;    
break;  //optional  
case value2:    
//code to be executed;    
break;  //optional  
......    
default:     
code to be executed if all cases are not matched;    
}    
C

Flow chart for switch

Sample Program

    #include<stdio.h>

    int main() {
      int number = 0;
      printf("enter a number:");
      scanf("%d", & number);
      switch (number) {
      case 10:
        printf("number is equals to 10");
        break;
      case 50:
        printf("number is equal to 50");
        break;
      case 100:
        printf("number is equal to 100");
        break;
      default:
        printf("number is not equal to 10, 50 or 100");
      }
      return 0;
    }
C

Output

Categorized in: