Card 07/ 08

ExerciseDifficulty: Intermediate1 min

Practice: Which Array Loops Throw or Skip an Element

Four loops over five elements: one throws, one silently drops one, two are correct.

Valid indexes run from 0 to length - 1, and a for-each loop has no index to get wrong. For each of the four loops below, decide whether it visits all five elements, visits too few, or throws, and on which pass. Write all four down before opening the answer.

java
String[] xs = {"a", "b", "c", "d", "e"};

for (int i = 0; i < xs.length; i++) { System.out.print(xs[i]); }
for (int i = 0; i <= xs.length; i++) { System.out.print(xs[i]); }
for (int i = 1; i < xs.length; i++) { System.out.print(xs[i]); }
for (String x : xs) { System.out.print(x); }
What each of the four loops does
Each loop, what it prints, and what went wrong
LoopPrintsVerdict
i = 0; i < lengthabcdeCorrect, and the form to write by default
i = 0; i <= lengthabcde then throwsReaches index 5, which does not exist
i = 1; i < lengthbcdeSilently drops the first element and never complains
for (String x : xs)abcdeCorrect, and cannot be off by one at all

The third is the dangerous one. It runs, it produces output, and the output is missing something: a bug that reaches a user rather than a stack trace that reaches you.

The fourth has no index to get wrong, which is why it is the right default. Reach for a counted loop only when you need the position.

← → move through sections and cards