0
0
Cprogramming~5 mins

Switch statement

Choose your learning style9 modes available
Introduction

A switch statement helps you choose between many options easily. It makes your code cleaner when you have many conditions to check.

When you want to run different code based on a variable's value.
When you have many fixed choices like menu options.
When you want to replace many if-else statements for clarity.
When you want to handle different cases for a number or character input.
Syntax
C
switch (expression) {
    case constant1:
        // code to run if expression == constant1
        break;
    case constant2:
        // code to run if expression == constant2
        break;
    // more cases...
    default:
        // code to run if no case matches
        break;
}

The expression is checked once.

Each case compares the expression to a constant value.

Examples
This example prints the day name for 1 or 2, or "Other day" if no match.
C
switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
    default:
        printf("Other day\n");
        break;
}
This example prints a message based on the grade character.
C
char grade = 'B';
switch (grade) {
    case 'A':
        printf("Excellent\n");
        break;
    case 'B':
        printf("Good\n");
        break;
    default:
        printf("Needs Improvement\n");
        break;
}
Sample Program

This program checks the value of number. It prints the matching case message. Since number is 3, it prints "Number is three".

C
#include <stdio.h>

int main() {
    int number = 3;
    switch (number) {
        case 1:
            printf("Number is one\n");
            break;
        case 2:
            printf("Number is two\n");
            break;
        case 3:
            printf("Number is three\n");
            break;
        default:
            printf("Number is something else\n");
            break;
    }
    return 0;
}
OutputSuccess
Important Notes

Always use break; to stop running other cases after a match.

The default case runs if no other case matches. It is optional but useful.

Cases must be constant values, not variables or expressions.

Summary

Switch statements help pick one action from many choices.

Use case for each choice and break; to stop.

default handles all other cases not listed.