Switch Statements

Lesson 17
Author : Afrixi
Last Updated : November, 2022
C++ - Programming Language
This course covers the basics of programming in C++.

Switch statements in C++ provide an alternative way to execute code based on the value of a variable or expression. Here’s an example of a program that uses a switch statement to convert a numeric grade to a letter grade:

#include <iostream>

int main() {
    int grade;

    std::cout << "Enter your numeric grade (0-100): ";
    std::cin >> grade;

    char letter_grade;

    switch (grade / 10) {
        case 10:
        case 9:
            letter_grade = 'A';
            break;
        case 8:
            letter_grade = 'B';
            break;
        case 7:
            letter_grade = 'C';
            break;
        case 6:
            letter_grade = 'D';
            break;
        default:
            letter_grade = 'F';
            break;
    }

    std::cout << "Your letter grade is: " << letter_grade << std::endl;

    return 0;
}

In this example, the program prompts the user to enter their numeric grade, reads in the input using std::cin, and then uses a switch statement to convert the grade to a letter grade. The switch statement takes the value of grade / 10 as its expression and evaluates it against several cases. If the expression matches a case, the corresponding code block is executed. If none of the cases match, the code block associated with the default case is executed.

Note that in this example, the switch statement does not include a break statement after each code block. This is because the cases for grades in the “A” and “B” ranges share the same code block. If a break statement were included after the “A” case, the code block for the “B” case would not be executed.