Tutorials › Loops & Repetition Simple Mode

Loops & Repetition

Use for loops to repeat things — draw rows, grids, patterns, and animations with just a few lines of code.

1

Repeating with For

A for loop repeats code a set number of times. It has three parts: a starting value (let i = 0), a condition to keep going (i < 8), and a step (i++ means "add 1"). Inside the loop, i is your counter — use it to control position!
0 / 10 lines
Loading editor...
size(400 200) draw: background(midnightblue) noStroke() for (let i = 0; i < 8; i++) { fill("hsl(" + (i * 45) + ", 80%, 65%)") circle(40 + i * 48 100 20) }
Try it!

Change the 8 to 20 — how many circles can you fit? Try changing the spacing too!

2

Grids with Nested Loops

Put one for loop inside another to make a grid! The outer loop handles rows (y), the inner loop handles columns (x). Multiply the counter by a spacing value to spread things out evenly.
0 / 19 lines
Loading editor...
size(400 300) draw: background(midnightblue) noStroke() for (let row = 0; row < 6; row++) { for (let col = 0; col < 8; col++) { let x = 30 + col * 50 let y = 30 + row * 45 if ((row + col) % 2 === 0) { fill(tomato) } else { fill(gold) rect(x y 40 35 4); } } }
Try it!

Change the colors to black and white to make a real checkerboard pattern!

3

Loops + Randomness

Loops are great for creating lots of objects at once. Combine a loop with random() to scatter shapes across the canvas. Here we create a starfield — each frame redraws the stars at random positions for a twinkling effect.
0 / 19 lines
Loading editor...
size(400 300) draw: background(midnightblue) noStroke() for (let i = 0; i < 80; i++) { let x = random(400) let y = random(300) let s = random(1 4) fill(255 random(150 255)) circle(x y s) fill(gold); circle(200 150 30); fill(30); textSize(14); text("Twinkling stars!" 150 280); }
Try it!

Try making the stars NOT twinkle — declare the star positions in setup() using an array instead!

4

Making Patterns

Combine loops with frameCount and math to create mesmerizing animated patterns. Each circle's position depends on both its index in the loop and the current frame — so the whole pattern moves smoothly over time.
0 / 15 lines
Loading editor...
size(400 300) draw: background(30) noStroke() for (let i = 0; i < 20; i++) { let angle = frameCount * 0.02 + i * 0.3 let r = 50 + i * 5 let x = 200 + Math.cos(angle) * r let y = 150 + Math.sin(angle) * r fill("hsl(" + (i * 18 + frameCount) + ", 80%, 60%)") circle(x y 10) }
Try it!

Try changing 0.02 to 0.05 to speed it up, or change 20 to 50 for more circles!

What to try next

  • Draw a row of houses using a for loop — each house at a different x position
  • Create a grid of emojis using nested loops and the text() function
  • Make a spiral pattern using a single loop with increasing radius and angle
  • Build an animated rain effect: use a loop and frameCount to make drops fall down the screen