Zone Of Makos

Menu icon

Switch Case Statements in C++

In the last lesson, we covered various conditional statements in C++, such as if statements and if-else statements, which allow us to make decisions based on certain conditions. In this lesson, we will explore another powerful conditional statement in C++ called the switch case statement. The switch case statement provides an alternative way to make decisions based on multiple possible values of a variable.

Syntax

The switch case statement in C++ has the following syntax:


switch (variable) {
    case value1:
        // Code to execute if variable equals value1
        break;
    case value2:
        // Code to execute if variable equals value2
        break;
    case value3:
        // Code to execute if variable equals value3
        break;
    default:
        // Code to execute if variable does not match any of the above cases
}

The switch statement starts with the keyword "switch" followed by the variable that you want to check against multiple values. Inside the switch block, you define individual cases using the keyword "case" followed by a specific value. If the value of the variable matches a particular case, the corresponding code block will be executed. The "break" statement is used to exit the switch block once a case is matched. If none of the cases match the variable value, the code block under the "default" case will be executed (optional).

Example Usage

Let's look at an example to understand how the switch case statement works in C++:


#include <iostream>

int main() {
    int day = 3;

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

    return 0;
}

In this example, the variable "day" is set to 3. The switch case statement checks the value of "day" against different cases. Since the value matches the case 3, the corresponding code block is executed, printing "Wednesday" to the console. The "break" statement ensures that the code execution exits the switch block once a case is matched.

Conclusion

The switch case statement in C++ provides a convenient way to make decisions based on multiple possible values of a variable. It is especially useful when you have a series of conditions to check against a single variable. By understanding and using the switch case statement, you can write more concise and readable code in C++. In the next lesson, we'll get into the topic: Iterative statements. Happy coding!