C Switch

The switch statement in C programming language allows us to select one of many code blocks to be executed based on the value of a variable or expression. The switch statement evaluates an expression and compares it with multiple constant values specified in the case labels. If the value of the expression matches any of the constant values, the corresponding code block is executed.

Here's the syntax of the switch statement in C programming language:

switch (expression) {
    case constant1:
        // code to be executed if expression == constant1
        break;
    case constant2:
        // code to be executed if expression == constant2
        break;
    .
    .
    .
    default:
        // code to be executed if expression does not match any of the constants
        break;
}

The expression in the above syntax is any expression that evaluates to an integer value or a character. The case labels are the constant values that are compared with the value of the expression. The default case is executed if the value of the expression does not match any of the constants.

Here's an example of the switch statement in C programming language:

#include <stdio.h>

int main() {
    char grade = 'B';

    switch (grade) {
        case 'A':
            printf("Excellent\n");
            break;
        case 'B':
            printf("Good\n");
            break;
        case 'C':
            printf("Average\n");
            break;
        case 'D':
            printf("Below Average\n");
            break;
        case 'F':
            printf("Fail\n");
            break;
        default:
            printf("Invalid grade\n");
            break;
    }

    return 0;
}

In the above example, we have used the switch statement to check the value of the grade variable and print the corresponding message. If the value of grade is 'B', the code block associated with the case 'B' label is executed, and the output will be "Good".

Note that the break statement is used in each case block to terminate the switch statement. If the break statement is not used, the control will flow to the next case block and execute its code as well.

Comments

Leave a Reply

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

84067