C++: Grades with switch

Turn marks into a grade using switch.

What to build

A switch on a value worked out from the input.

Requirements

  • 90 to 100 is A, 80 to 89 is B, 70 to 79 is C, and below 70 is F.
  • Print invalid for marks below 0 or above 100.
  • Use switch.

Input

One whole number.

Output

One line.

Constraints

The marks can be any value that fits in an int.

Example

Input:

95

Output:

A

Why it works

Integer division groups all the marks of one band under a single number, which is exactly what switch needs.

Examples

Example 1 · Input
95
Expected output
A
Example 2 · Input
75
Expected output
C

Hints

Hint 1

marks / 10 turns the marks into one digit.

Hint 2

Several cases can share a block.

Hint 3

Handle invalid marks before the switch.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;

int main() {
    int marks;
    cin >> marks;
    if (marks < 0 || marks > 100) {
        cout << "invalid" << endl;
        return 0;
    }
    switch (marks / 10) {
    case 10:
    case 9:
        cout << "A" << endl;
        break;
    case 8:
        cout << "B" << endl;
        break;
    case 7:
        cout << "C" << endl;
        break;
    default:
        cout << "F" << endl;
    }
    return 0;
}

Lesson: Decisions and loops →