Practice question · Put in order
Order the parts of a correct while loop so that it counts up and then stops.
- Check the condition before the pass: is i < 5 ?
- Run the body of the loop
- Return to check the condition again
- Initialize the counter: i = 0
- Update the counter toward the condition becoming false: i = i + 1
Hints
- A while loop tests its condition before each pass, so the counter must exist first.
- The update must run inside the loop, or the condition never becomes false.
Show the answer
- Initialize the counter: i = 0
- Check the condition before the pass: is i < 5 ?
- Run the body of the loop
- Update the counter toward the condition becoming false: i = i + 1
- Return to check the condition again
Why
Initialize, then test, run the body, update, and loop back to test again. Omitting the update is the classic infinite loop: the condition stays true forever because nothing moves the counter toward making it false.
Practise Loops and Repeated Computation
The app has 6 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on Loops and Repeated Computation
- Match each loop keyword or form to what it does.
- Modifying a list while looping over it can silently skip elements. Why does removing an item mid-iteration…
- The counter starts at i = 0. Select every loop below that runs its body exactly 5 times.
- An off-by-one error in a loop boundary usually causes a crash, which is what makes it easy to find.