C Switch Statement

πŸ”„ C Switch Statement – Multi-Way Decision Making

The switch statement in C is used when you want to perform different actions based on the value of a variable. It’s like a menu: depending on what you choose, something specific happens.

πŸ”Ή Syntax of switch

switch (expression) {
    case value1:
        // code block
        break;
    case value2:
        // code block
        break;
    ...
    default:
        // default code block
}

πŸ“ Example: Simple Switch Case

This program displays the day of the week based on a number.

#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("Weekend!\n");
    }

    return 0;
}
  

Try It Now

πŸ“ Example: Switch with User Input

Let’s ask the user to enter a number and display a message using switch.

#include <stdio.h>

int main() {
    int option;
    printf("Enter a number (1-3): ");
    scanf("%d", &option);

    switch (option) {
        case 1:
            printf("You chose ONE\n");
            break;
        case 2:
            printf("You chose TWO\n");
            break;
        case 3:
            printf("You chose THREE\n");
            break;
        default:
            printf("Invalid choice!\n");
    }

    return 0;
}
  

Try It Now

🎯 Key Points

  • switch works with int and char types.
  • Each case must end with a break to prevent fall-through.
  • default is optional and runs if no case matches.

πŸŽ‰ Practice Time!

Change the values and try different switch structures. Want to build a mini calculator using switch? You totally can!