← All lessons/Loops· Lesson 15 of 32

Counting with i

Use the loop counter i in calculations to spread shapes out across the canvas.

About 7 min

The counter is a number you can use

Last lesson the circles piled up in one spot because we drew them all at the same x. But i changes every pass — 0, 1, 2, 3, 4 — so we can do math with it to move each shape.

If x = i * 40, then the circles land at 0, 40, 80, 120, 160 — neatly spaced 40 pixels apart. Multiplying the counter is the key trick:

Spacing circles out with i * 40.

Why the + 30?

Adding a number shifts everything over so the first circle isn't jammed against the edge. i * 40 sets the spacing; + 30 sets the starting offset.

You can use i in any calculation — for the size, the color, or the position. That's how a few lines of code can draw a whole pattern.

Your turn

Draw a spaced-out row of 6 circles. Use a for loop that runs 6 times, and call ellipse(i * 50 + 50, 200, 40, 40) so each x is calculated from i.

Hints