What is switch Statement in C++?

The switch statement is used to execute one block of code from multiple options based on the value of a variable.

It compares the value with different cases and runs the matching one.

Syntax of switch Statement

switch (expression) {

    case value1:
        // code to execute
        break;

    case value2:
        // code to execute
        break;

    default:
        // code if no match is found
}

Explanation:

  • The expression is evaluated once.
  • Its value is compared with each case value.
  • If a match is found, that case block executes.
  • break is used to stop execution after a case.
  • default runs when no case matches.

Algo of Switch Statement

  1. First, the value of the expression is checked.
  2. Then it is compared with each case.
  3. When a match is found, that case runs.
  4. break stops the program from checking further cases.
  5. If no case matches, default executes.

Example

#include <iostream>
using namespace std;

int main() {
    int day = 2;

    switch (day) {
        case 1:
            cout << "Monday";
            break;
        case 2:
            cout << "Tuesday";
            break;
        case 3:
            cout << "Wednesday";
            break;
        default:
            cout << "Invalid Day";
    }

    return 0;
}

Output:

Tuesday

Explanation:

  • The value of day is 2.
  • It matches with case 2.
  • So, "Tuesday" is printed.
  • break stops further execution.

Summary:

  • switch statement is used to select one option from many.
  • It works with fixed values instead of conditions.
  • break prevents unwanted execution.
  • Without break, multiple cases can execute.
  • default handles unmatched cases.

Welcome to ShikshaSanchar!

ShikshaSanchar is a simple and helpful learning platform made for students who feel stressed by exams, assignments, or confusing topics. Here, you can study with clarity and confidence.

Here, learning is made simple. Notes are written in easy English, filled with clear theory, code examples, outputs, and real-life explanations — designed especially for students like you who want to understand, not just memorize.

Whether you’re from school, college, or someone learning out of curiosity — this site is for you. We’re here to help you in your exams, daily studies, and even to build a strong base for your future.

Each note on this platform is carefully prepared to suit all levels — beginner to advanced. You’ll find topics explained step by step, just like a good teacher would do in class. And the best part? You can study at your pace, anytime, anywhere.

Happy Learning! – Team ShikshaSanchar