Bonus Points

The teacher has found out that one question in the test was worded wrong. So everyone gets 3 bonus points. But nobody can have more than 50 points, because that's the most the test could give.

This time, the function changes the data. So it gets the vector as a reference without const: std::vector<int>&. Then it works with the vector from main() directly, and the changes stay in it after the function ends. Change the elements in an index loop:

#include <iostream>
#include <vector>

void doubleAll(std::vector<int>& numbers) {
    for (int i = 0; i < numbers.size(); i++) {
        numbers[i] *= 2;
    }
}

int main() {
    std::vector<int> numbers = {1, 2, 3};
    doubleAll(numbers);
    std::cout << numbers[0] << " " << numbers[1] << " " << numbers[2] << std::endl;
    return 0;
}
2 4 6

numbers[i] is the element in the vector itself. In a for (int n : numbers) loop, n would be only a copy of the element, and the change wouldn't get into the vector.

Common mistakes:

  • Without the &, the function gets a copy of the vector. It changes the copy, and the results still show the old scores.
  • With const, the compiler doesn't allow the change:
main.cpp:54:19: error: cannot assign to return value because function 'operator[]' returns a const value

The call goes in main(), above printResults(names, scores): first the scores change, then they're printed. The other way round, the old scores would be printed.

Instructions

Under printResults() (above main()), write a function void addPoints(std::vector<int>& scores, int bonus) that adds bonus to each element of scores in a loop.

In main(), above the call of printResults(), add addPoints(scores, 3);. Every student now has 3 more points, and the results start like this:

TEST RESULTS
Adam: 45 points, grade A
Emma: 41 points, grade B

Adam has exactly 45 points, so he gets an A. If he has a B, check that the condition for an A in grade() uses >=. If the scores haven't changed, the & is missing from the parameter. Finn now has 51 points out of 50. You'll fix that in the next step.

Change addPoints(): if a student has more than 50 points after the addition, set their score to 50. Then the results look like this:

TEST RESULTS
Adam: 45 points, grade A
Emma: 41 points, grade B
Finn: 50 points, grade A
Jack: 17 points, grade F
Lucy: 30 points, grade C
Average score: 36.6
Best: Finn (50 points)

If Lucy with 30 points has a D, check the >= in the condition for a C.

Start programming for free

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

Or sign up with:

5/7