C-switch case with example



What is switch case statement in c:


Switch case statement is also a conditional statement like if-else. When we have multiple options and for these options we need to do different task than we use Switch case statement like we can use switch case statement for making calculator etc.

syntax of switch case statement:



switch (variable or an integer expression)
{
     case constant:
     //C Statements
     ;
     case constant:
     //C Statements
     ;
     default:
     //C Statements
     ; 
}


Flow chart for switch case:









Example for switch case statement:


problem statement: In this problem statement we need to make a basis calculator by using the SWITCH CASE statement


#include<stdio.h
void main(){

    int a,b,output;
    char operation;
    printf("Enter an Expression: ");
    scanf("%d%c%d",&a,&operation,&b);

        switch(operation)
        {
            case '+':
            	output = a + b;
                break;

            case '-':
            	output = a - b;
                break;

            case '*':
            	output = a * b;
                break;}
        printf("Result= %d" , result);



Problem statement: In this problem statement we have some grade for the student and we are going to find the mean of grade like if student get "A" it means "Excellent" .....



#include <stdio.h>
 
int main () {

   /* local variable definition */
   char grade = 'B';

   switch(grade) {
      case 'A' :
         printf("Excellent!\n" );
         break;
      case 'B' :
      case 'C' :
         printf("Well done\n" );
         break;
      case 'D' :
         printf("You passed\n" );
         break;
      case 'F' :
         printf("Better try again\n" );
         break;
      default :
         printf("Invalid grade\n" );
   }
   
   printf("Your grade is  %c\n", grade );
 
   return 0;
}