DSA FUNDAMENTALS › ARRAY BASICS
The array [4, 2, 7, 1] stores 4 at index 0, 2 at index 1, 7 at index 2, and 1 at index 3. To print it in reverse order, read the elements from index 3 down to index 0. That produces 1 7 2 4, even though the stored array is still [4, 2, 7, 1].
cout << arr[3] << " ";
cout << arr[2] << " ";
cout << arr[1] << " ";
cout << arr[0];Printing and rearranging are separate actions. Printing only reads values and sends them to the output. Swapping would change which value is stored at each index, but reverse printing needs no assignment and no swap.
Must [4, 2, 7, 1] be swapped before it can produce 1 7 2 4?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
Here n is 4, so the array has four positions numbered 0, 1, 2, and 3. The last valid index is n - 1, which is 3. A reverse loop must therefore start its loop variable at 3.
int n = 4;
int i = n - 1; // i is 3Starting at i = n would start at 4. There is no index 4 in this array, so the first access would already be outside the array. In C++, accessing an array outside its valid indices is undefined behaviour, which means the program may print a wrong value, appear to work, or fail.
Fill in the initialization for a reverse loop over n = 4.
for (int i = _____; i >= 0; i--) {
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 loop starts at i = 3 and must move toward smaller indices. The update i-- changes the loop variable from 3 to 2, then 1, then 0. The condition i >= 0 allows index 0 to be visited, so the values are printed as 1 7 2 4.
| I BEFORE THE VISIT | VALUE READ | OUTPUT SO FAR |
|---|---|---|
| 3 | 1 | 1 |
| 2 | 7 | 1 7 |
| 1 | 2 | 1 7 2 |
| 0 | 4 | 1 7 2 4 |
for (int i = n - 1; i >= 0; i--) {
cout << arr[i] << " ";
}After the body runs for i = 0, the update i-- makes i equal to -1. The condition i >= 0 is then false, so the loop stops before trying to access arr[-1]. The direction, stopping condition, and starting index together visit every valid index exactly once.