Last time we saw while
loops repeat until a condition becomes false
. Let's explore why making sure that condition can change is so important.
Engagement Message
What did we say would happen if a while
loop's condition never becomes false
?
When a while
loop's condition never becomes false
, it creates an infinite loop. The program gets stuck repeating the same code forever! This can freeze the application or browser tab.
Have you ever had a program that seemed "stuck" and wouldn't respond? An infinite loop might have been the cause!
Engagement Message
What do you think we need to do to prevent them?
The most common cause of an infinite loop is forgetting to update the variable that is being checked in the condition.
Engagement Message
Why will this loop run forever?
To avoid infinite loops, you must ensure that something inside the loop's body eventually makes the condition false
.
In our counter example, we need to add count++
(or count = counter + 1) inside the loop. This guarantees that will eventually become 5 or greater, stopping the loop.
