Lesson 4 of 5

🔄 Loops & Patterns

Repeat code to create amazing patterns

🔁 Why Loops?

What if you want to draw 100 circles? You don't want to writecircle() 100 times! Loops let you repeat code automatically.

🔢 The for Loop

🔑 for Loop Syntax

for (let i = 0; i < 10; i++) {
  // This code runs 10 times
  // i goes: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
}

let i = 0 — Start at 0

i < 10 — Keep going while i is less than 10

i++ — Add 1 to i each time (same as i = i + 1)

💡 We use i * 40 to space them out. When i=0, x=20. When i=1, x=60. When i=2, x=100...

🎨 Using i for Everything

The loop variable i can control anything: position, size, color!

📐 Nested Loops: Grids!

Put a loop inside another loop to create a grid — one loop for rows, one for columns.

🎉 100 circles with just a few lines of code!

🎲 Adding Randomness

random(min, max) gives you a random number between min and max. Great for generative art!

👆 This creates a new pattern every frame! (That's why it flickers)

✨ Static Random (Starfield)

To keep random positions fixed, use randomSeed()or generate positions once in setup:

➗ The Modulo Trick

% (modulo) gives the remainder after division. It's great for creating alternating patterns!

i % 2 gives 0, 1, 0, 1, 0, 1... (alternating!)

i % 3 gives 0, 1, 2, 0, 1, 2... (three colors)

🏆 Challenge: Gradient Grid

Create a grid where the color gradually changes based on position. Use row and col to calculate the color values!

🎨 Final Project: Generative Art

Create your own generative art piece! Ideas:

  • • Concentric circles (circles inside circles)
  • • Spiral pattern
  • • Random line art
  • • Mosaic with random colors

📝 What You Learned

Concepts

  • ✅ for loops repeat code
  • ✅ Nested loops create grids
  • ✅ random() for variety
  • ✅ % modulo for patterns

Syntax

  • for (let i=0; i<n; i++)
  • random(min, max)
  • randomSeed(n)
  • i % n