Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › C++ FUNDAMENTALS
Consider this declaration: int scores[5] = {12, 7, 19, 4, 10}; It creates exactly five int elements. The 5 tells C++ how many slots to allocate for scores. It does not name one of those slots. To access a stored value, you use an index, and the first index is 0.
int scores[5] = {12, 7, 19, 4, 10};Because counting starts at 0, five elements need the indices 0, 1, 2, 3, and 4. The declaration's number and the largest usable index are different: the element count is 5, while the final valid index is one less, or 4.
What does the 5 mean in int scores[5] = {12, 7, 19, 4, 10};?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
Each index identifies one position in the same array. For scores, scores[0] is 12, scores[1] is 7, scores[2] is 19, scores[3] is 4, and scores[4] is 10. There is no sixth slot belonging to scores. Writing scores[5] asks for a position immediately beyond the five allocated elements.
| INDEX | VALUE |
|---|---|
| 0 | 12 |
| 1 | 7 |
| 2 | 19 |
| 3 | 4 |
| 4 | 10 |
| 5 | Outside the array |
In this assignment, the right-hand side is evaluated first: scores[1] = scores[0] + scores[3]. The program reads scores[0], which is 12, and scores[3], which is 4. Their sum is 16. The left-hand index, 1, identifies the only slot that receives the new value.
int scores[5] = {12, 7, 19, 4, 10};
scores[1] = scores[0] + scores[3];
// scores is now {12, 16, 19, 4, 10}The values at indices 0 and 3 are used as inputs, not changed by the expression. Index 1 changes from 7 to 16, while indices 0, 2, 3, and 4 keep their original values.
Enter the complete array after scores[1] = scores[0] + scores[3].
scores[1] = scores[0] + scores[3];Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
For this array, the condition i < 5 permits i to be 0, 1, 2, 3, and 4. Those are exactly the five valid indices, so every element is visited once. When i becomes 5, the condition is false and the loop stops before trying to access scores[5].
for (int i = 0; i < 5; i++) {
cout << scores[i] << " ";
}Changing the condition to i <= 5 adds one unwanted iteration. The loop still visits indices 0 through 4, then allows i to equal 5 and attempts scores[5]. The problem is not the number of valid values already printed. The problem is that the condition permits an index outside the array.