Lesson 6 of 12

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:

  1. Reach a decision diamond (the loop condition).
  2. If the condition is true: do the loop body, then follow the back arrow to the diamond again.
  3. 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.

Start SET count = 5 count > 0? Yes OUTPUT count count = count - 1 No "Blast off!" End
BEGIN
  SET count = 5
  WHILE count > 0
    OUTPUT count
    count = count - 1
  END WHILE
  OUTPUT "Blast off!"
END

Variable Watch

VariableValue
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
1st5Yes5
2nd4Yes4
3rd3Yes3
4th2Yes2
5th1Yes1
6th check0No — 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:

  1. Setup — set the starting value (count = 5)
  2. Condition — the check that keeps the loop running (count > 0)
  3. 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