CPP Tutorial



C++ SWITCH


Switch Statement in C++

The switch statement allows you to select one of many code blocks to execute, based on the value of a variable or expression. It’s a cleaner alternative to multiple if-else statements when checking a variable against several constant values.

πŸ“ Syntax

switch (expression) {
    case constant1:
        // code to execute if expression == constant1
        break;
    case constant2:
        // code to execute if expression == constant2
        break;
    ...
    default:
        // code to execute if no case matches
}
  

πŸ”Ž How It Works

  • The expression is evaluated once.
  • Its value is compared with each case constant.
  • If a match is found, the corresponding block runs.
  • break exits the switch; without it, execution falls through to the next case.
  • default runs if no cases match (optional but recommended).

πŸ’‘ Example

#include <iostream>
using namespace std;

int main() {
    int day;
    cout << "Enter day number (1 to 7): ";
    cin >> day;

    switch (day) {
        case 1:
            cout << "Monday" << endl;
            break;
        case 2:
            cout << "Tuesday" << endl;
            break;
        case 3:
            cout << "Wednesday" << endl;
            break;
        case 4:
            cout << "Thursday" << endl;
            break;
        case 5:
            cout << "Friday" << endl;
            break;
        case 6:
            cout << "Saturday" << endl;
            break;
        case 7:
            cout << "Sunday" << endl;
            break;
        default:
            cout << "Invalid day number" << endl;
    }

    return 0;
}
  

βš™οΈ Explanation

- The program reads a number from 1 to 7.
- The switch matches this number to the corresponding day name.
- break statements prevent "fall through" β€” without them, all subsequent cases would run.
- If the number is not between 1 and 7, the default case prints an error message.

Summary

  • Use switch for clear, readable multiple-choice decision making.
  • Each case checks one possible value.
  • break prevents executing unwanted cases.
  • default handles unexpected values.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review