• Home
  • 2.5 switch Statement

2.5 switch Statement

View Categories

2.5 switch Statement

< 1 min read

Table of Contents

The switch statement selects one block of code based on the value of an expression. Each possible value is associated with a case label.

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

        default:
            printf("Invalid day\n");
    }

    return 0;
}

Example Output #

Wednesday

Explanation #

The expression inside switch is evaluated:

switch (day)

Here, day has the value 3, so execution starts at:

case 3:

The corresponding statement executes:

printf("Wednesday\n");

The break statement then exits the switch statement.

If none of the case labels matches the value of day, the default block executes.

The switch expression is evaluated once, and control is transferred to the matching case label.

Powered by BetterDocs

Leave a Reply

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