Switch statement in C Language

0


 Switch statement in C Language



GAIN AND SHINE



Introduction to Switch Statement in C

    In C programming, the switch statement is a powerful control structure that allows you to execute different blocks of code based on the value of a specific variable or expression. It provides an efficient alternative to using multiple if-else statements in certain scenarios. In this blog, we will explore the switch statement in C, understand its syntax, and provide examples to illustrate its usage.


Syntax of Switch Statement

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

switch (expression) {

case constant1:

        // Code block to be executed if expression matches constant1

        break;

    case constant2:

        // Code block to be executed if expression matches constant2

        break;

    case constant3:

        // Code block to be executed if expression matches constant3

        break;

    ...

    default:

        // Code block to be executed if expression doesn't match any constant

}


    Here, expression is evaluated and compared with the constants specified in the case statements. If a match is found, the corresponding code block is executed. The break statement is used to terminate the switch statement. If no match is found, the code block inside the default statement is executed.


Example of Switch Statement

Let's consider an example to understand the switch statement in C:

#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;

        default:

            printf("Invalid day\n");

    }


    return 0;

}


Output:

Wednesday

    In this example, the variable day is initialized with the value 3. The switch statement evaluates the value of day and matches it with the corresponding case. Since day is equal to 3, the code block inside the case 3 statement is executed, printing "Wednesday" to the console.


Conclusion

    The switch statement in C provides an efficient way to execute different blocks of code based on the value of a variable or expression. It eliminates the need for multiple if-else statements in certain scenarios, improving the readability and maintainability of the code. However, it's important to remember to use the break statement to terminate each case block and include a default statement to handle cases where the expression doesn't match any constant. The switch statement is a powerful tool in your programming toolkit, enabling you to write more structured and concise code.



Post a Comment

0Comments

Share Your Feedback Here !!

Post a Comment (0)