Grades

Every result gets a grade. The teacher gives it by the score:

  • 45 to 50 points: A
  • 38 to 44 points: B
  • 30 to 37 points: C
  • 20 to 29 points: D
  • fewer than 20 points: F

That's a choice between several options, which is what else if is for. Put it in a function that gets the score and returns the grade. A function can have more than one return, and a condition decides which one runs. The grade is a letter, so the function returns a char: write char before its name, and return letters in single quotes, like 'A'. For example, T-shirt sizes:

#include <iostream>

char shirtSize(int height) {
    if (height < 150) {
        return 'S';
    } else if (height < 175) {
        return 'M';
    } else {
        return 'L';
    }
}

int main() {
    std::cout << shirtSize(140) << std::endl;
    std::cout << shirtSize(160) << std::endl;
    std::cout << shirtSize(185) << std::endl;
    return 0;
}
S
M
L

The order of the conditions matters. The program tries them from the top and runs only the first one that's true. So each next condition is tried only when none of the earlier ones was true. Someone 140 cm tall also meets height < 175, but the program never gets to that condition. In grade(), start with the highest limit. If the first condition were score >= 20, it would be true for Finn with 48 points too, and he'd get a D.

Watch the limits as well: 45 points is still an A, so the condition is score >= 45, not score > 45.

And watch the quotes: "A" in double quotes is text (a string), not a char, and the compiler reports an error:

main.cpp:8:16: error: cannot initialize return object of type 'char' with an lvalue of type 'const char[2]'

Write the new function above printResults(), which will call it. If it were below, the compiler wouldn't know it yet at the place of the call, and it would report an error:

main.cpp:9:76: error: use of undeclared identifier 'grade'

You can call a function that returns a value right inside the output: std::cout << grade(scores[i]) prints the grade of the student with index i.

Instructions

Above printResults(), write a function char grade(int score) that returns 'A' for 45 points or more, 'B' for 38 or more, 'C' for 30 or more, 'D' for 20 or more and 'F' otherwise.

In printResults(), add a comma, a space, the word grade, a space and the grade computed by grade() to the end of each student's line:

Adam: 42 points, grade B
Emma: 38 points, grade B
Finn: 48 points, grade A
Jack: 14 points, grade F
Lucy: 27 points, grade D

If Emma with 38 points has a C, check that the condition for a B uses >=.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/7