Repeated Elements

Draw four circles by writing four calls to circle.

function setup() {
	createCanvas(windowWidth, windowHeight);
	background(100);
}

function draw() {
	circle(50, 50, 20);
	circle(50, 100, 20);
	circle(50, 150, 20);
	circle(50, 200, 20);
}

Add two more circles by adding two more lines of code.

function draw() {
	circle(50, 50, 20);
	circle(50, 100, 20);
	circle(50, 150, 20);
	circle(50, 200, 20);
	circle(50, 250, 20);
	circle(50, 300, 20);
}

Source code repetition: advantages

There is a simple correspondence between lines of code, and generated graphics.

It is easy to change just one repeated element.

function draw() {
	circle(50, 50, 20);
	circle(50, 100, 20);
	circle(50, 150, 50);
	circle(50, 200, 20);
	circle(50, 250, 20);
	circle(50, 300, 20);
}

Source code repetition: disadvantages

Changing many elements requires editing many lines of code.

function draw() {
	circle(50, 50, 50);
	circle(50, 100, 50);
	circle(50, 150, 50);
	circle(50, 200, 50);
	circle(50, 250, 50);
	circle(50, 300, 50);
}

Drawing a large number of elements would require a lot of code.

function draw() {
	circle(50, 50, 50);
	circle(50, 100, 50);
	circle(50, 150, 50);
	circle(50, 200, 50);
	circle(50, 250, 50);
	circle(50, 300, 50);
	// …
}

Preparing for iteration

We will prepare the code for iteration the same way that a different sequence prepared it to use functions: by making the repeated sections of source code look more similar to each other.

Let's pare back to four circles, and demonstrate a different way to repeat multiples.

function draw() {
	circle(50, 50, 40);
	circle(50, 100, 40);
	circle(50, 150, 40);
	circle(50, 200, 40);
}

Introduce a variable, so that the calls to circle all look the same.