DSA FUNDAMENTALS › ARRAY BASICS
Take the array [8, 3, 5, 1, 9, 6] with n = 6. To print alternate elements from the first element, select indices 0, 2, and 4. Those positions contain 8, 5, and 9, so the output is 8 5 9. The values are mixed: 8 is even, 5 is odd, and 9 is odd. Their value properties do not select them. Their positions do.
| INDEX | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Value | 8 | 3 | 5 | 1 | 9 | 6 |
| Selected? | yes | no | yes | no | yes | no |
Which indices produce 8 5 9 when selecting alternate elements from [8, 3, 5, 1, 9, 6] starting at the first element?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
Start the loop index at 0, continue while it is less than n, and add 2 after each visit. The loop accesses array[0], then array[2], then array[4]. After the last access, the update changes i to 6, so the next condition check stops the loop.
for (int i = 0; i < n; i += 2) {
cout << arr[i] << ' ';
}i = 0 -> print arr[0] = 8
update i to 2
i = 2 -> print arr[2] = 5
update i to 4
i = 4 -> print arr[4] = 9
update i to 6
i = 6 -> condition i < n is falseFor n = 6, valid indices run from 0 through 5. The final useful index in this pattern is 4. The update then changes i from 4 to 6, and i < n is false, so the loop stops before trying to access array[6].
for (int i = 0; i < n; i += 2) {
cout << arr[i] << ' ';
}
// Wrong condition:
for (int i = 0; i <= n; i += 2) {
cout << arr[i] << ' ';
}Complete the C++ loop header so it visits indices 0, 2, and 4 without accessing index 6.
for (int i = ___; i ___ n; i ___ 2) {
cout << arr[i] << ' ';
}Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The step of 2 creates alternating positions, but the starting index decides which half of those positions you visit. Starting at index 1 would visit 1, 3, and 5, producing 3 1 6. That is the other alternating pattern. To make the output begin with the first element, keep the loop initialization at i = 0.
for (int i = 1; i < n; i += 2) {
cout << arr[i] << ' ';
}The two starting choices cover different positions in the same array. Starting at 0 selects 0, 2, and 4, giving 8 5 9. Starting at 1 selects 1, 3, and 5, giving 3 1 6. The required pattern here is the first one because it starts with the array's first element.