Theoretical recap.
A while loop repeats a block of instructions as long as a condition remains true.
Its structure is simple.
You define a starting point, an initialization, a condition that is tested before each iteration, and an update inside the loop that eventually makes the condition false.
If the update is missing or wrong, the condition never becomes false and you get an infinite loop, the single most common mistake with while.
Mental model.
Imagine a counter starting at 1.
Before each repetition, you ask a question.
Is my counter still less than or equal to n? If yes, you execute the body.
For example, display the counter, then increment it by 1.
If no, you stop.
The loop is a controlled repetition governed entirely by the condition.
Mini example, pseudocode.
I equals 1. while i less than equals n.
Display i. i equals i plus 1.
With n equals 5, this prints 1, 2, 3, 4, 5.
Common errors, forgetting i equals i plus 1, infinite loop, starting at 0 instead of 1, or using less than instead of less than equals and missing the last value.
Always verify your initialization, your condition, and your increment.
These three elements must work together.
Read the full transcript.
Create an account to read the whole episode, search across every transcript, and follow the shows you care about.
Theoretical recap.
A while loop repeats a block of instructions as long as a condition remains true.
Its structure is simple.
You define a starting point, an initialization, a condition that is tested before each iteration, and an update inside the loop that eventually makes the condition false.
If the update is missing or wrong, the condition never becomes false and you get an infinite loop, the single most common mistake with while.
Mental model.
Imagine a counter starting at 1.
Before each repetition, you ask a question.
Is my counter still less than or equal to n? If yes, you execute the body.
For example, display the counter, then increment it by 1.
If no, you stop.
The loop is a controlled repetition governed entirely by the condition.
Mini example, pseudocode.
I equals 1. while i less than equals n.
Display i. i equals i plus 1.
With n equals 5, this prints 1, 2, 3, 4, 5.
Common errors, forgetting i equals i plus 1, infinite loop, starting at 0 instead of 1, or using less than instead of less than equals and missing the last value.
Always verify your initialization, your condition, and your increment.
These three elements must work together.