So far every line of your code ran once. A loop changes that: it runs the same block of code many times, usually with a counter that changes each time. That counter is a variable you can use — to set positions, colours, sizes, anything.
This session gives you three experiments you can run live. Use them to build intuition before you see nested loops in c06.
for loop — three parts, one lineThe loop above draws 8 circles. On the first run, i = 0 → circle at x = 20. On the second, i = 1 → circle at x = 70. And so on until i = 8, which fails the condition i < 8 and stops the loop.
Press Step → once for each iteration. Watch i grow, the condition get checked, and one circle appear. Change the limit with the slider, then reset and step through again.
iThe third part of the for loop can do more than just add 1. Here are the four operator families, with shorthand for each:
| Operator | Means | Example | |
|---|---|---|---|
| i++ | i = i + 1 | 0, 1, 2, 3, 4 … | count up by ones |
| i += 3 | i = i + 3 | 0, 3, 6, 9, 12 … | count up by threes |
| i-- | i = i − 1 | 10, 9, 8, 7 … | count down |
| i -= 10 | i = i − 10 | 100, 90, 80 … | count down by tens |
| i *= 2 | i = i × 2 | 1, 2, 4, 8, 16, 32 … | double each time ← geometric! |
Pick an operator below. See how the same canvas fills up differently — more circles, fewer circles, different spacing.
while loop — when you don't know how many timesA for loop is perfect when you know the count up front. A while loop keeps going as long as a condition is true — useful when you stop based on a value, not a fixed count:
You can't easily write this as a for loop, because you don't know in advance how many times it takes before size drops below 3.
Each press adds one ring. Watch the size variable shrink. Notice how many iterations it takes — the computer figures that out for you.
i isn't just a counter — it's a number you can feed into any formula. Use it as x position (i * 50), as a colour (i * 30 for hue), as a size (100 - i * 8), or all three at once. Every different formula gives a different visual from the same loop.
i++ generates an arithmetic sequence (constant difference = 1). i *= 2 generates a geometric sequence (constant ratio = 2). The loops you just experimented with are the same patterns from Lessons 8 and 9 — just running at computer speed.
i *= 2 (from 1). Only 9 circles appear even though i shoots up to 256. Try to predict: what is i on each circle? (Hint: 1, 2, 4, …)for loop code (in your own p5 editor) to colour each circle differently: fill(i * 30, 100, 200). What changes?while loop (in your editor) that starts at let n = 1 and doubles it each time (n *= 2) until n > 500. Draw a circle of diameter n at the centre. How many circles appear?for loop, draw lines from mouseX, mouseY to (i * 42, 0) — one line per value of i. Move the mouse. What happens?