Example. Printing Array Elements (In reverse order)
[comp1110-72]
Example. Printing Array Elements (In reverse order)
[comp1110-72]In the lecture, we went through the following example of looping through an array.
Note that, in contrast to earlier, we start our counter variable at the end (i = arr.length),
and reduce it before we use it in the body of the loop.
It is always a good idea to sanity-check your indices to prevent off-by-one errors (which would crash your program). Often, it suffices to look at the first and last index values.
In this case, i starts as arr.length, but the first valid index from the back is arr.length - 1.
Since we assign i to be i - 1 before looking at the array, that works out fine.
For the last index, the loop will end when i == 0, so the last time it could run is when i == 1.
In that case, because we again reduce i before accessing the array, the last index we will look at is 0,
which is both a valid index if the array is not empty (in which case, we would not be in the loop to begin with),
and also the last index we want to look at.
Finally, the loop invariant (§ [comp1110-0W]) tracks the property that we wanted, which is that all elements of the array within a certain range have been printed, in such a way that the range coincides with the full array at the end of the loop.