While Loops
Imagine you're doing push-ups. You do one, check "have I done 10 yet?" — no — so you do another one. You keep repeating until you've done 10. That's a while loop: keep doing something as long as a condition is true.
A while loop repeats a set of steps over and over, as long as a condition stays true. Once the condition becomes false, the loop stops and the program moves on.
What Makes a Loop Different?
Until now, every flowchart we've seen goes downward — from Start to End in one direction. A loop is different because it has an arrow that goes back up. That "back arrow" is what makes steps repeat.
Here's the pattern:
- Reach a decision diamond (the loop condition).
- If the condition is true: do the loop body, then follow the back arrow to the diamond again.
- If the condition is false: exit the loop and continue downward.
Example: Rocket Countdown
Let's build a countdown timer: start at 5, count down to 1, then say "Blast off!" Watch the back arrow — it's what makes the loop repeat. Step through this carefully and watch the variables change.
BEGIN
SET count = 5
WHILE count > 0
OUTPUT count
count = count - 1
END WHILE
OUTPUT "Blast off!"
END
Variable Watch
| Variable | Value |
|---|---|
| Step through to see variables | |
Did you see the dashed back arrow? That's the loop! After decreasing
count, it goes back up to the diamond to check the condition again.
This repeats until count is no longer greater than 0.
Here's what happens at each pass through the loop:
| Loop pass | count value | count > 0? | Output |
|---|---|---|---|
| 1st | 5 | Yes | 5 |
| 2nd | 4 | Yes | 4 |
| 3rd | 3 | Yes | 3 |
| 4th | 2 | Yes | 2 |
| 5th | 1 | Yes | 1 |
| 6th check | 0 | No — exit loop | — |
Watch out for infinite loops! If the condition never becomes false,
the loop runs forever and the program gets stuck. That's why we decrease count
inside the loop — it makes sure the loop will eventually stop.
The Three Parts of Every Loop
Every while loop needs three things to work correctly:
- Setup — set the starting value (
count = 5) - Condition — the check that keeps the loop running (
count > 0) - Update — change something so the condition eventually becomes false (
count = count - 1)
If you forget the update step, you get an infinite loop. If you forget the setup, the variable might not exist. All three parts are essential.
Key Takeaways
- A while loop repeats steps as long as a condition is true.
- In a flowchart, the back arrow (going upward) is what makes it a loop.
- Every loop needs: a setup (starting value), a condition (when to stop), and an update (change something each time).
- When the condition becomes false, the loop exits and the program continues.
- Forgetting the update step causes an infinite loop — the program gets stuck forever.
- In pseudocode:
WHILE condition ... END WHILE