Explain switch statement in C language


It is used to select one among multiple decisions. ‘switch’ successively tests a value against a list of integers (or) character constant. When a match is found, the statement (or) statements associated with that value are executed.

Syntax

The syntax is given below −

switch (expression){
   case value1 : stmt1;
      break;
   case value2 : stmt2;
      break;
   - - - - - -
   default : stmt – x;
}

Algorithm

Refer the algorithm given below −

Step 1: Declare variables.
Step 2: Read expression variable.
Step 3: Switch(expression)
   If value 1 is select : stmt 1 executes break (exists from switch)
   If value 2 is select : stmt 2 executes ;break
   If value 3 is select : stmt 3 executes; break
   ……………………………………………
Default : stmt-x executes;

Example

The following C program demonstrates the usage of switch statement −

 Live Demo

#include<stdio.h>
main ( ){
   int n;
   printf ("enter a number");
   scanf ("%d", &n);
   switch (n){
      case 0 : printf ("zero");
         break;
      case 1 : printf ("one");
         break;
      default : printf ("wrong choice");
   }
}

Output

You will see the following output −

enter a number
1
One

Consider another program on switch case as mentioned below −

Example

 Live Demo

#include<stdio.h>
int main(){
   char grade;
   printf("Enter the grade of a student:
");    scanf("%c",&grade);    switch(grade){       case 'A': printf("Distiction
");          break;       case 'B': printf("First class
");          break;       case 'C': printf("second class
");          break;       case 'D': printf("third class
");          break;       default : printf("Fail");    }    printf("Student grade=%c",grade);    return 0; }

Output

You will see the following output −

Run 1:Enter the grade of a student:A
Distiction
Student grade=A
Run 2: Enter the grade of a student:C
Second class
Student grade=C

Updated on: 15-Mar-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements