We've now learned both for
loops and while
loops. They're both powerful tools for repetition, but when should you choose one over the other?
Engagement Message
Which type of loop do you think would be better for printing your name 10 times?
Use a for
loop when you know the number of iterations ahead of time. This includes iterating over every item in a collection (like an array) or using a specific, counted range.
This is for definite iteration—when the number of repetitions is known before the loop starts.
Engagement Message
Can you give an example of a situation where using a for
loop is the best choice?
Use a while
loop when you need to repeat something until a certain condition changes, but you don't know how many times that will take.
This is for indefinite iteration—the number of repetitions is not known in advance.
Engagement Message
Think of a video game. When might you use a while
loop for a player's turn?
Here's a helpful way to think about it:
for
= "Do this X times" or "Do this for each item."- = "Keep doing this as long as this condition is true."
