switch statements

Home / C Programming / switch statements

switch statements


C programming, the `switch` statement provides a way to perform different actions based on the value of a variable or an expression. It allows you to select one of several code blocks to execute, depending on the value of the controlling expression.

The basic syntax of the `switch` statement in C is as follows:

switch (expression) {

    case constant1:

        // code to execute if expression matches constant1

        break;

    case constant2:

        // code to execute if expression matches constant2

        break;

    // more case statements

    default:

        // code to execute if expression doesn't match any constant

}


The `expression` is evaluated, and its value is compared with the constant values specified in each `case` statement. If a match is found, the corresponding code block is executed. The `break` statement is used to exit the `switch` statement once a match is found. If no match is found, the code block within the `default` case is executed.Here's an example to illustrate the usage of `switch` statement:

#include <stdio.h>

int main() {

    int day = 3;

    switch (day) {

        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("Invalid day\n");

    }

   printf("Program complete.\n");

    return 0;

}