Section 1 - Instruction

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?

Section 2 - Instruction

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?

Section 3 - Instruction

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?

Section 4 - Instruction

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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal