KatInterview

For Loop vs While Loop: Picking the Right Tool

System DesignModel answer
EasyModel answerSystem Designcontrol-flowloopsreadability

Last updated

Explain when to reach for a for loop versus a while loop, covering intent, safety, and how each choice affects the risk of infinite loops.

Loop Selection: More Than a Style Choice

Every language that supports iteration gives you at least two options: a for loop and a while loop. They can both express the same logic in most cases, but choosing the wrong one for the situation often results in code that is harder to read, easier to break, or more likely to loop forever.

What You Need to Cover

  1. Describe the core conceptual difference between for and while loops. What kind of problem is each one designed for?
  2. Give a concrete scenario where a while loop is the cleaner or safer choice.
  3. Give a concrete scenario where a for loop is clearly preferable.
  4. Explain how infinite loops happen and how your choice of loop structure affects the chances of accidentally writing one.

Scenario to Reason Through

You have a list of numbers and a threshold value. You want to collect numbers from the list in order, but stop as soon as you encounter one that exceeds the threshold. You do not know in advance how many items you will collect.

numbers = [10, 20, 35, 40, 50]
threshold = 30

# Expected result: [10, 20]
# 35 exceeds the threshold, so we stop before including it.

# How would you write this with a for loop? With a while loop?
# Which version better communicates the intent?

Walk through both implementations, note any trade-offs, and discuss the following edge cases:

  • The list is empty
  • The very first element exceeds the threshold
  • No element exceeds the threshold (all items get collected)
  • An element is exactly equal to the threshold — should it be included?

Hints

Hint 1

Think about what each loop type says to the reader. A for loop says 'I am visiting each item in this thing.' A while loop says 'I am waiting for a condition to become false.' Which description fits your problem better?

Hint 2

Index management is where while loops go wrong on collections. Count how many places you have to write or read the index in each version — that number tells you roughly how many places there are to make a mistake.

Hint 3

An infinite loop happens when nothing in the loop body is guaranteed to move the termination condition closer to being true. For each version you write, ask: what strictly changes on every iteration that eventually makes the loop stop?