while and do...while
Same false condition, different result: while skips its body, do...while runs it once.
Loops repeat a block of code: for when you know how to count the repeats, while when you repeat until a condition changes, and do...while when the body must run at least once. Most loop bugs are off-by-one errors and conditions that never become false.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Print the numbers from 10 down to 1, then Lift off!.
Using a while loop, find how many times you can halve 1000 (with / 2) before it is less than 1.
Print a staircase of # signs with 4 rows: #, ##, ###, ####.
Explain it without notes
Describe the three parts of a for loop and the order in which they run.
When would you choose while over for, and do...while over while?
What is an off-by-one error? Give an example and how to avoid it.
Why does an infinite loop freeze the whole page?
Console
(nothing was printed)Expected console output
2024 has 4 digits
first power of 2 above 1000: 1024 after 10 doublings
do...while body ran with b = 10