← All lessons/Loops· Lesson 17 of 32

Nested loops

Put a loop inside a loop to fill the canvas with a grid of shapes.

About 8 min

A loop inside a loop

One loop draws a row. To draw a whole grid, put one loop inside another. The outer loop steps down the rows (y), and for each row the inner loop runs all the way across the columns (x).

If the outer loop runs 3 times and the inner loop runs 3 times, the inner body runs 3 × 3 = 9 times total — one shape per grid cell.

Two loops nested to draw a 3×3 grid.

Two counters

Use a different name for each counter — like x and y — so the inner loop doesn't overwrite the outer one. Each shape's position comes from combining both.

Change the < 3 to a bigger number and the spacing to match, and you can tile the canvas with dozens of shapes from just four lines of code.

Your turn

Draw a 3×3 grid of circles with nested for loops. The outer loop steps y from 0 to 2, the inner loop steps x from 0 to 2, and inside you draw ellipse(x * 100 + 100, y * 100 + 100, 60, 60) — that's 9 circles.

Hints