Programming Fundamentals · Interview question

Why does continue inside a while loop sometimes cause an infinite loop, but not inside a for?

A strong answer

In a for loop, the update clause is part of the loop header and always runs after the body, including after a continue. So for (i = 0; i < n; i++) { if (skip()) continue; ... } still increments i each iteration. In a while loop, there is no separate update step; you typically update the counter inside the body. If continue jumps over that update, the counter never changes, the condition stays true, and you loop forever: while (i < n) { if (skip()) continue; ...; i++; } is a textbook infinite loop. The fix is either to put the update before any potential continue, or to restructure the loop so the early-skip uses a different mechanism.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

for Loops, break & continue

The counted loop you'll write most often, plus the two escape hatches: break to leave early, continue to skip an iteration.

More for Loops, break & continue questions

Browse all 472 interview questions
Why does continue inside a while loop sometimes cause an infinite loop, but not inside a for? | EmbeddedPrep.io