A loop that stops moving
A medium Java puzzle in the logic and control flow family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 7. Play this one as a puzzle without the answer.
What is wrong
When a negative value is found, continue jumps back to the loop condition without incrementing i, so the same element is examined forever and the program hangs after printing 3.
The fix
How to avoid it next time
Prefer a for loop when the index changes every iteration, or make sure every path advances the loop variable.
Want the background? Read Loops, labels and do-while in the Java concepts library.
About logic and control flow
Operator precedence, missing break statements, short-circuit evaluation and loop conditions that never change are simple to write and tiring to spot after a long day of reviews.
In code review: Read conditions out loud with explicit parentheses, check every switch branch for break or return, and make sure each loop makes progress toward its exit.
More puzzles in this family
Frequently asked questions
What is the bug in "A loop that stops moving"?
When a negative value is found, continue jumps back to the loop condition without incrementing i, so the same element is examined forever and the program hangs after printing 3. The faulty line is line 7: continue;
How do I fix it?
Replace it with: if (data[i] < 0) { i++; continue; } // or use a for loop, which increments in the header. Prefer a for loop when the index changes every iteration, or make sure every path advances the loop variable.
How do I catch logic and control flow in code review?
Read conditions out loud with explicit parentheses, check every switch branch for break or return, and make sure each loop makes progress toward its exit.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.