Loops

Repeat code with loops to create patterns.

For Loop

Use for i in 0..n to repeat code n times:

fn setup() { size(300, 200) } fn draw() { background(rgb(30, 30, 40)) // Draw 5 circles for i in 0..5 { let x = 50 + i * 55 fill(hsl(i * 60, 70, 60)) circle(x, 100, 25) } }

Nested Loops

Put loops inside loops to create grids:

fn setup() { size(300, 200) } fn draw() { background(rgb(30, 30, 40)) for row in 0..4 { for col in 0..6 { let x = 30 + col * 45 let y = 30 + row * 45 let hue = (row * 6 + col) * 15 fill(hsl(hue, 70, 60)) circle(x, y, 18) } } }

Range Function

Use range(start, end, step) for more control:

fn setup() { size(300, 200) } fn draw() { background(rgb(30, 30, 40)) // Count by 30: 0, 30, 60, 90... for x in range(30, 280, 50) { fill(coral) circle(x, 100, 20) } }

While Loop

Use while to loop while a condition is true:

fn setup() { size(300, 200) } fn draw() { background(rgb(30, 30, 40)) let x = 20 let size = 10 while x < 280 { fill(hsl(x, 70, 60)) circle(x, 100, size) x = x + size + 5 size = size + 3 } }

Loop Control

Use break to exit a loop early, or continue to skip to the next iteration:

fn setup() { size(300, 200) } fn draw() { background(rgb(30, 30, 40)) for i in 0..10 { // Skip every other circle if i % 2 == 0 { continue } let x = 20 + i * 30 fill(coral) circle(x, 100, 15) } }