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 35. 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.