Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › C++ FUNDAMENTALS
A function does not need to receive an array just because it uses one. totalScores() can declare the local array scores, read its four elements, and keep the array inside its own scope. The function owns the data it creates, so no array argument is needed.
int totalScores() {
int scores[4] = {6, 3, 8, 5};
int total = 0;
for (int i = 0; i < 4; i++) {
total += scores[i];
}
return total;
}During the loop, scores[i] selects one element at the current index. The four selected values are 6, 3, 8, and 5, and total grows from 0 to 6, then 9, then 17, and finally 22. The array is available because the loop runs inside totalScores(), where the local variable exists.
Where does scores = [6, 3, 8, 5] exist when it is declared inside totalScores()?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The whole array and one indexed element are different expressions. scores names the array, while scores[i] produces one int value. That value can be passed to addScore just like any other function argument, so the helper receives only the current score and the current total.
int addScore(int total, int score) {
return total + score;
}
int totalScores() {
int scores[4] = {6, 3, 8, 5};
int total = 0;
for (int i = 0; i < 4; i++) {
total = addScore(total, scores[i]);
}
return total;
}At i = 2, the current total is 9 and scores[i] means scores[2], which is 8. The call is addScore(9, 8). Inside addScore(), total is 9 and score is 8, so the returned value is 17. totalScores() then stores that returned value back in total.
Complete the call that processes index 2.
addScore(total, ______);Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The remaining calls continue the same way. After the call at i = 2, total is 17. At i = 3, scores[3] is 5, so addScore(17, 5) returns 22. totalScores() returns that int to its caller, while its local scores array remains inside the function.
| I | SCORES[I] | TOTAL BEFORE CALL | TOTAL AFTER CALL |
|---|---|---|---|
| 0 | 6 | 0 | 6 |
| 1 | 3 | 6 | 9 |
| 2 | 8 | 9 | 17 |
| 3 | 5 | 17 | 22 |
main can store or print the 22 returned by totalScores() because 22 is the value that crossed the function boundary. It cannot use scores after totalScores() finishes, because scores is a local variable whose scope ends with that function. Referring to scores from main would be a compile-time error, even though totalScores() successfully used the array.