Computer Science I / Loops and Repeated Computation
Practice question · Select all that apply

The counter starts at i = 0. Select every loop below that runs its body exactly 5 times.

Hints
  1. Count the values each loop actually visits, watching the < versus <= boundary.
  2. range(1, 6) stops before 6, and while i <= 5 runs one pass more than while i < 5.
Show the answer
  • A. for i in range(1, 6)
  • B. while i < 5 (with i = i + 1 each pass)
  • E. for i in range(5)
Why

range(5) gives 0..4 and while i < 5 from 0 gives 0..4, both 5 passes; range(1, 6) gives 1..5, also 5. But while i <= 5 runs 0..5, which is 6 passes, and while i < 4 runs 0..3, only 4. The <= versus < boundary is the exact off-by-one to watch.

Read the lesson: Loops and Repeated Computation →

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