Looping Statements

Lesson 4 of 20

Meet for, while and do-while — three ways to repeat work, plus the traps that make loops run forever.

The big picture

Three ways to repeat

Same idea, three dialects: for when you know the count, while when you do not, do-while when the body must run at least once.

for

Bundles init; condition; update on one line — best when the number of passes is known.

while

Checks first, runs after. A false condition from the start means zero passes.

do-while

Runs the body first, checks later — the body always executes at least once.

break & continue

break exits the loop early; continue skips straight to the next pass.