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
- 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. - Read the score into an
intnamedscorewithscores[i]. - Declare
string grade;as an empty string, to be filled by the ladder. - Test for A:
score >= 90setsgradeto"A". - Add
else if (score >= 80)for"B". - Add
else if (score >= 70)for"C". - Add
else if (score >= 60)for"D". - End with
elsefor"F", which also closes the ladder. - Print inside the loop, after the ladder:
names[i], then": ", thengrade, thenendl. 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:
| i | names[i] | score | first true test | printed |
|---|---|---|---|---|
| 0 | Alice | 92 | >= 90 | Alice: A |
| 1 | Bob | 78 | >= 70 | Bob: C |
| 2 | Carol | 85 | >= 80 | Carol: B |
| 3 | Dan | 67 | >= 60 | Dan: 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. Ifscoreswere 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
coutafter the closing brace would print once, for whatever the variables held last (andgradewould no longer be in scope). - Starting at 1 or using
<=. Vectors are indexed from 0, soi <= (int) names.size()reads one element too many. - Reusing a grade between students. If
gradewere 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.
