C++ Switch Case

How do switch case statements work in C++?

Switch Case

The 'switch' statement is a control flow statement that allows a variable to be tested for equality against a list of values. It provides a way to streamline multiple 'if-else' statements when checking a single variable against different values. The basic syntax of a 'switch' statement looks like this:

switch (expression) {
    case value1:
        // code to be executed if expression equals value1
        break;
    case value2:
        // code to be executed if expression equals value2
        break;
    // more cases as needed
    default:
        // code to be executed if none of the cases match
}

Explanation:

'switch': Keyword that initiates the switch statement.

'expression': The variable or expression that is being tested.

'case value1': A specific value that 'expression' is being compared against.

'// code to be executed': The block of code that is executed if 'expression' matches the specified value.

'break': Keyword that exits the switch statement. If omitted, execution will "fall through" to the next case.

'default': Optional case that is executed if none of the cases match. It's similar to the 'else' in an 'if-else' statement.

Here's a simple example:

cpp Copy Code
#include<iostream>

int main() {
    int day = 3;

    switch (day) {
        case 1:
            std::cout << "Monday\n";
            break;
        case 2:
            std::cout << "Tuesday\n";
            break;
        case 3:
            std::cout << "Wednesday\n";
            break;
        default:
            std::cout << "Other day\n";
    }

    return 0;
}
Output:
Wednesday

* If 'day' is 3, it will print "Wednesday" because it matches the corresponding case. If 'day' is not 1, 2, or 3, it will print "Other day" due to the 'default' case.

Using switch case with characters:

You can also use the 'switch' statement with characters in a similar way as with integers. Here's an example:

cpp Copy Code
#include<iostream>

int main() {
    char grade;

    // Get user input for the grade
    std::cout << "Enter your grade: ";
    std::cin >> grade;

    switch (grade) {
        case 'A':
            std::cout << "Excellent\n";
            break;
        case 'B':
            std::cout << "Good\n";
            break;
        case 'C':
            std::cout << "Average\n";
            break;
        case 'D':
            std::cout << "Below Average\n";
            break;
        case 'F':
            std::cout << "Fail\n";
            break;
        default:
            std::cout << "Invalid grade\n";
    }

    return 0;
}
Output:
Enter your grade: B
Good

This program prompts the user to enter their grade, and then the 'switch' statement checks the entered grade and prints the corresponding message.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.