Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › C++ FUNDAMENTALS
Suppose scores has five positions and i currently equals 2. The statement cin >> scores[i] consumes one integer from the input and stores it at scores[2]. It does not fill scores[0], scores[1], scores[3], or scores[4]. The subscript scores[i] selects one destination for that one extraction.
const int n = 5;
int scores[n];
int i = 2;
cin >> scores[i];If the next typed value is 19, the result of this statement is that scores[2] becomes 19. The other positions are not filled by that statement. To fill all five positions, you need five extractions and a way to change the destination between them.
Given i = 2 and an extraction that consumes 19, which position receives the value?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
An indexed for loop performs one extraction for each value of i from 0 through 4. On every iteration, cin >> scores[i] consumes the next integer and sends it to the position named by the current i. The loop condition i < n gives five iterations because n is 5.
const int n = 5;
int scores[n];
for (int i = 0; i < n; i++) {
cin >> scores[i];
}| ITERATION | CONSUMED VALUE | DESTINATION | ARRAY AFTER THE WRITE |
|---|---|---|---|
| i = 0 | 12 | scores[0] | [12, _, _, _, _] |
| i = 1 | 7 | scores[1] | [12, 7, _, _, _] |
| i = 2 | 19 | scores[2] | [12, 7, 19, _, _] |
| i = 3 | 4 | scores[3] | [12, 7, 19, 4, _] |
| i = 4 | 10 | scores[4] | [12, 7, 19, 4, 10] |
The five values are not placed into scores all at once. The loop performs five separate extractions: 12 goes to scores[0], 7 goes to scores[1], 19 goes to scores[2], 4 goes to scores[3], and 10 goes to scores[4]. The final state is scores = [12, 7, 19, 4, 10].
Complete the subscript so this loop reads five values into indices 0-4.
for (int i = 0; i < n; i++) {
cin >> scores[?];
}Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
For integer input, spaces and line breaks both separate one value from the next. These separators do not choose array positions. The loop still decides the destination with scores[i], so the input 12 7 19 4 10 produces the same array whether all five values appear on one line or each value appears on a separate line.
const int n = 5;
int scores[n];
for (int i = 0; i < n; i++) {
cin >> scores[i];
}
// The following input layouts have the same result:
// 12 7 19 4 10
//
// 12
// 7
// 19
// 4
// 10The first extraction always takes the first integer token, the second takes the next token, and so on. With either layout, the first token 12 reaches scores[0], the third token 19 reaches scores[2], and the last token 10 reaches scores[4]. The final state remains scores = [12, 7, 19, 4, 10].