C Switch Case Statement With Example

Switch case in C programming

The Switch case is a specified multi-way decision-maker that tests whether an expression produces one of several static values.

In other words, the switch statement causes a particular group of statements to be select from several available groups the selection is based upon the current value of an expression i.e to include within the switch statements.

switch (expression){
    case constants1:
      // statements
      break;
 
    case constants2:
      // statements
      break;
    .
    .
    .
    default:
      // default statements
}

Structure of switch case:

SWITCH CASE STATEMENT

Example of switch case:

#include <stdio.h>
#include<stdlib.h>
int main()
{
   int x;
   printf("Enter a number\n");
   scanf("%d",&x);
   switch (x)
   {
       case 1: printf("Monday\n");
               break;
       case 2: printf("Tuesday\n");
                break;
       case 3: printf("Wednesday\n");
              break;
       case 4: printf("Thursday\n");
              break;
       case 5: printf("Friday\n");
              break;
       case 6: printf("Saturday\n");
              break;
       case 7: printf("Sunday\n");
              break;
       default: printf("Wrong Choice");
                break;
   }
   return 0;
}
 

Output:

Enter a number
2
Tuesday

Calculator using switch case in C:

#include <stdio.h>
#include <stdlib.h>
 
int main() {
    char calculator;
   int num1, num2;
 
    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &calculator);
    printf("Enter two numbers: ");
    scanf("%d %d",&num1, &num2);
 
    switch(calculator)
    {
        case '+':
            printf("%d + %d = %d",num1, num2, num1+num2);
            break;
 
        case '-':
            printf("%d - %d = %d",num1, num2, num1-num2);
            break;
 
        case '*':
            printf("%d * %d = %d",num1, num2, num1*num2);
            break;
 
        case '/':
            printf("%d / %d = %d",num1, num2, num1/num2);
            break;
 
        // if operator does not match any case constant +, -, *, /
        default:
            printf("Wrong Operator");
    }
 
    return 0;
}
 
Enter an operator (+, -, *, /): +
Enter two numbers: 5 4
5 + 4 = 9

Previous Lecture:

Introduction to C
Escape Characters
Data Types

If you have any problem in solving your questions, then join our Telegram group or search @Learnsimply, we will help you.

Please write comments if you find anything incorrect in the C switch case statements lecture.

Leave a Comment

en English
X