C Switch Statement

The switch statement in C is a control flow statement that simplifies decision-making processes in programs. It allows a program to test a variable against a series of values and perform different actions based on the value of the variable.

The syntax for a switch statement is as follows:

switch (expression) {
   case value1:
      // code to be executed if expression matches value1
      break;
   case value2:
      // code to be executed if expression matches value2
      break;
   ...
   default:
      // code to be executed if none of the values match
}

In this syntax, the “expression” is the variable or expression to be tested, and each “case” represents a possible value of the expression. If the expression matches a particular value, the code following that case statement will be executed. The “break” statement is used to exit the switch statement and continue with the rest of the program.

If none of the values match, the code following the “default” statement will be executed.

Example:

#include <stdio.h>

int main() {
   int day = 4;
   
   switch (day) {
      case 1:
         printf("Monday");
         break;
      case 2:
         printf("Tuesday");
         break;
      case 3:
         printf("Wednesday");
         break;
      case 4:
         printf("Thursday");
         break;
      case 5:
         printf("Friday");
         break;
      default:
         printf("Invalid day");
   }
   
   return 0;
}

In this example, the switch statement tests the value of the “day” variable against a series of values representing the days of the week. If the value matches a particular day, the name of that day is printed on the screen. If the value does not match any of the days, the default message “Invalid day” is printed.

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial