Skip to main content
Logo image

Subsection Which to Use: for vs. while

Both for-loops and while-loops repeat code, but they serve different purposes. Choose the loop that matches your situation to make your code easier to read and understand.
Table 37. Comparing for-loops and while-loops
Feature for-loops while-loops
Requires a fixed list of values (often 1:N) a logical condition
Behavior repeats once per value in the list repeats while the condition is true
Terminates after the last value is used when the condition becomes false
Best when you know exactly how many iterations you need you do not know how many iterations you will need
Technically, any for-loop can be rewritten as a while-loop and vice versa. However, using the loop that naturally fits the problem makes your code clearer.

Checkpoint 38.

(a) When to use a for-loop.

When is a for-loop most appropriate?
  • When you know how many times to repeat code.
  • A for-loop works with a fixed list of values, making it ideal when you know the number of iterations in advance.
  • When you need to repeat until a condition becomes false.
  • This describes a while-loop, not a for-loop.
  • When you need to skip certain iterations.
  • Both for-loops and while-loops can skip iterations using continue.
  • When you don’t know how many times to repeat code.
  • If the number of iterations is unknown, a while-loop is more appropriate.

(b) For-loop requires a list of values.

    A for-loop requires a fixed list of values to iterate through.
  • True.

  • Unlike while-loops which use a condition, for-loops need a list of values (like 1:10 or [2, 4, 6, 8]).
  • False.

  • Unlike while-loops which use a condition, for-loops need a list of values (like 1:10 or [2, 4, 6, 8]).

(c) Choosing the right loop type.

Which loop should you use when you don’t know in advance how many iterations are needed?
  • A for-loop
  • A for-loop requires knowing the number of iterations (or a list of values) in advance.
  • A while-loop
  • A while-loop is perfect when the number of iterations depends on a condition that changes during execution.
  • Either one works equally well
  • While technically interchangeable, a while-loop is clearer and more natural when the iteration count is unknown.
  • Neither, you need an if-statement
  • An if-statement doesn’t repeat code. You need a loop for repetition.

(d) Loops are interchangeable.

    Technically, any for-loop can be rewritten as a while-loop and vice versa.
  • True.

  • Both loop types can accomplish the same tasks, but choosing the one that fits naturally makes your code easier to read and understand.
  • False.

  • Both loop types can accomplish the same tasks, but choosing the one that fits naturally makes your code easier to read and understand.