Start learning free

LESSON 200 OF 667 · PROJECTS: EVERYDAY PROGRAMS

Report Card V4 in C++: Grading a Class with a Loop over Two Vectors

Practice Read the full explanation

Combine lists, loops, and conditionals to print a letter grade for each student in a class.

You start with:

vector<string> names = {"Alice", "Bob", "Carol", "Dan"};
vector<int> scores = {92, 78, 85, 67};

Build:

Alice: A
Bob: C
Carol: B
Dan: D

Rules:

  • Loop over the indices of the students (names.size()) so you can read the name and the score at the same position.
  • Use the same scale as V3: 90+ A, 80-89 B, 70-79 C, 60-69 D, below 60 F.
  • On each iteration print the name, a colon and a space, then the grade, for example Alice: A.

Use vector<string> and vector<int> with index loops.

vector<string> names = {"Alice", "Bob", "Carol", "Dan"};
vector<int> scores = {92, 78, 85, 67};

for (int i = 0; i < (int) names.size(); i++) {
    int score = scores[i];
    string grade;
    if (score >= 90) {
        grade = "A";
    } else if (score >= 80) {
        grade = "B";
    } else if (score >= 70) {
        grade = "C";
    } else if (score >= 60) {
        grade = "D";
    } else {
        grade = "F";
    }
    cout << names[i] << ": " << grade << endl;
}

STEP 1 OF 9
    Ctrl + Enter to check

    C++ · PROJECTS: EVERYDAY PROGRAMS

    Report Card V4 in C++, explained

    Problem overview

    Version 4 grades a whole class. The starter code has two parallel vectors: names holds Alice, Bob, Carol and Dan, and scores holds 92, 78, 85 and 67. The score at position i belongs to the name at position i. The program prints one line per student, with the name, a colon, a space and the letter grade:

    Alice: A
    Bob: C
    Carol: B
    Dan: D
    

    The grading scale is the one from the previous version, where one score became one letter. Now the same ladder runs once for every student.

    Approach: one index, two vectors

    Because the vectors line up, a single counter i can read from both. A for loop runs i through 0, 1, 2 and 3. In each pass, the body reads scores[i], turns it into a grade with the if / else if / else ladder, and prints names[i] next to it.

    The ladder tests from the top: 90 or more is A, 80 or more is B, and so on. Each test only needs a lower limit, because a score that reaches it already failed the tests above. The final else gives F.

    Declaring grade inside the loop body is deliberate. Each pass gets a fresh, empty string, so a grade from one student can't leak into the next.

    Why an index loop here

    C++ also has a range-based loop, for (string name : names), which is shorter when you need one vector only. Here the program needs two values at once, a name and its score, and a range-based loop over names has no position to hand to scores. An index loop gives you that position. The price is that you maintain the three parts of the header yourself: the start, the condition and the step. Each of them is a place where an off-by-one mistake can hide.

    Keeping the vectors parallel is a simple way to store related data, but it depends on you never changing one without the other. If you inserted a student into names and forgot scores, every grade after that position would be paired with the wrong name, and nothing in the program would warn you. For four students this is manageable, and the lesson uses it to practise loops.

    Step by step

    1. Write the loop header. int i = 0; i < (int) names.size(); i++ visits every position once. Close the loop's brace right away and put the next steps inside it.
    2. Read the score into an int named score with scores[i].
    3. Declare string grade; as an empty string, to be filled by the ladder.
    4. Test for A: score >= 90 sets grade to "A".
    5. Add else if (score >= 80) for "B".
    6. Add else if (score >= 70) for "C".
    7. Add else if (score >= 60) for "D".
    8. End with else for "F", which also closes the ladder.
    9. Print inside the loop, after the ladder: names[i], then ": ", then grade, then endl. Because it sits in the loop body, it runs once per student and gives four lines.

    The solution in C++

    vector<string> names = {"Alice", "Bob", "Carol", "Dan"};
    vector<int> scores = {92, 78, 85, 67};
    
    for (int i = 0; i < (int) names.size(); i++) {
        int score = scores[i];
        string grade;
        if (score >= 90) {
            grade = "A";
        } else if (score >= 80) {
            grade = "B";
        } else if (score >= 70) {
            grade = "C";
        } else if (score >= 60) {
            grade = "D";
        } else {
            grade = "F";
        }
        cout << names[i] << ": " << grade << endl;
    }
    

    Here is what each pass does with the starter data:

    inames[i]scorefirst true testprinted
    0Alice92>= 90Alice: A
    1Bob78>= 70Bob: C
    2Carol85>= 80Carol: B
    3Dan67>= 60Dan: D

    Why the (int) cast

    names.size() returns an unsigned type (size_t), while i is a signed int. Comparing a signed and an unsigned value makes the compiler convert the signed one, and that conversion goes wrong for negative numbers. The cast (int) names.size() makes both sides signed, so the loop compares like with like. The difference shows up as soon as you subtract: for an empty vector, names.size() - 1 doesn't give -1 but 18446744073709551615 on a 64-bit system, because unsigned values wrap around at zero. With the cast, (int) names.size() - 1 is -1, as you'd expect.

    Edge cases and common mistakes

    • Vectors of different lengths. The loop uses the length of names. If scores were shorter, scores[i] would read past the end, and that is undefined behaviour: no error, and unpredictable values. The lesson's data always has the same number of each.
    • Printing outside the loop. A cout after the closing brace would print once, for whatever the variables held last (and grade would no longer be in scope).
    • Starting at 1 or using <=. Vectors are indexed from 0, so i <= (int) names.size() reads one element too many.
    • Reusing a grade between students. If grade were declared before the loop, a missing branch would silently repeat the previous student's grade. Declaring it inside prevents that.
    • The boundaries. A score of exactly 90 is an A, and exactly 60 is a D. Use >=.

    Testing

    Run the starter data and compare it with the four lines above. Then change a score to a boundary value, such as 90 for Bob, and confirm that his line becomes Bob: A.

    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free