Switch statement in C

In this lesson, we will learn about the switch case in C programming.

What is a switch case statement in C?

A switch-case statement is a simplified version of an if-else statement. It’s a multi-way decision statement that evaluates only one variable.

Syntax of the switch case statement in C

Switch(variable) {
  case value1;
  statement block 1;
  break;
  case value2;
  statement block 2;
  break;
  case valueN;
  statement blockN;
  break;
}

The switch case statement compares the value inside the switch statement with the value of each case statement. When both the values matches, then the statement block of that particular case gets executed. We generally use a default statement inside the switch case because, in any condition, if the value of the switch statement and case statement don’t get matched then the statement block inside the default gets executed.

Flow chart of the switch case statement

Example of the switch statement in C

#include<stdio.h>

Int main() {
  Int foodno;
  printf(“please enter your choice from 1 to 5”);
  scanf(“\n % d”, & foodno);

  switch (foodno) {
  case 1:
    printf(“\n BURGER\ N”);
    break;
  case 2:
    printf(“PIZZA\ n”);
    break;
  case 3:
    printf(“SANDWHICH\ n”);
    break;
  case 4:
    printf(“NOODLES\ n”);
    break;
  case 5:
    printf(“\nINDIAN THALI\ n”);
    break;
  default:
    printf(“It’ s a wrong choice”);
  }
  return 0;
}

Output

Enter any number from 1 to:

5

INDIAN THALI

Explanation: As the user enters an integer value between 1 to 12, the switch statement compares that value with the given test cases. The above example user enters 5, so the statement block to case 5 gets executed, and we get INDIAN THALI as output and break statement terminates the switch statement’s body. If any wrong input is provided, then the default statement gets executed.

Summary

  • Switch-case statement is a simplified version of the if-else statement.
  • It is a multi-way decision statement that evaluates only one variable.
  • The switch statement can also be nested.
  • The switch case statement is easy to debug and gets executed faster as compared to the if-else statement.
  • Its maintenance is easier.

 

Back to: Learn C Programming > Control Statements in C

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.