Looping Statements

Lesson 4 of 20

Stop copy-pasting work: for, while and do-while repeat for you — follow one animated iteration at a time.

The big picture

Repeat without repeating yourself

A loop runs the same block again and again — with a counter or a condition deciding when to stop.

for

Know the count? for (int i = 1; i <= 4; i++) packs init, test and update in one line.

while

Repeat while a condition holds — the test runs first, the body after.

do-while

The body runs once before the first check — perfect for menus.

The update

i++ moves the loop toward its end. Forget it and the loop never stops.

Off by one

i < 4 runs 4 times; i <= 4 runs 5. One character, one extra pass.