Skip to main content

Switch statement in decision making

Short answer

switch evaluates an expression once, compares it with constant case labels, and executes the matching block. break exits the switch; default handles no match. For instance, a day number input prints the day name, making multi‑way selection cleaner than multiple if‑else.

How is the switch statement used in decision making? Explain with a suitable example.

The switch statement selects one of many blocks of code by comparing the value of an integer or character expression with the constant values of the case labels. The matching case is executed; break leaves the switch; default runs when no case matches.

Syntax:

switch (expression)
{
    case value1: statements; break;
    case value2: statements; break;
    default: statements;
}

Example:

#include <stdio.h>
int main(void)
{
    int day;
    printf("Enter day number (1-7): ");
    scanf("%d", &day);
    switch (day)
    {
        case 1: printf("Sunday\n");    break;
        case 2: printf("Monday\n");    break;
        case 3: printf("Tuesday\n");   break;
        case 4: printf("Wednesday\n"); break;
        case 5: printf("Thursday\n");  break;
        case 6: printf("Friday\n");    break;
        case 7: printf("Saturday\n");  break;
        default: printf("Invalid day\n");
    }
    return 0;
}

For input 3:

Enter day number (1-7): Tuesday

It makes multi-way decisions simple and more readable than a long if-else ladder.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →