Switch case in c

The switch case statement is used when we have multiple options and we need to perform a different task for each Switch statement in C tests the value of a variable and compates it with multiple cases. Once the case match is found, a block of Statements associated with that particular case is executed.

Syntax of Switch statements:

 switch(expression) 

{

  case x:

    // code block

    break;

  case y:

    // code block

    break;

  default:

    // code block

    break;

}                                                                                          Flow Diagram of Switch case statement:

 

Examples of Switch case in c:
Let’s take a simple example to understand the working of Switch case statements…..

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;

  case 6:

    printf(“Saturday”);

    break;

  case 7:

    printf(“Sunday”);

    break;

}

 

                   // Outputs         “Thursday” (day 4)

Examples 2:
#include <stdio.h>
    int main() {
        int num = 8;
        switch (num) {
            case 7:
                printf(“Value is 7”);           // topperworld.in
                break;
            case 8:
                printf(“Value is 8”);
                break;
            case 9:
                printf(“Value is 9”);
                break;
            default:
                printf(“Out of range”);
                break;
        }
        return 0;
    }
                                             // output= Value is 8

Leave a Comment

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