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);
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/587ee4d3-cf8c-469e-93c3-174fa8be1d70/Untitled.png

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);
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/012e9a7c-9279-4cb7-ae3a-0269a67ad114/Untitled.png

Source code repetition: advantages

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

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/e0d147c5-0b86-4e8b-970b-600c694f37b3/Artboard.png

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);
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/353bc533-dbeb-4829-a112-c44d8d4ed0d6/Untitled.png

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);
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/8b961d83-d8e6-4fe5-a26c-f97152bdfd0b/Untitled.png

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);
	// …
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/c1155ac0-378e-4c1a-a227-f830e5c79d66/Untitled.png

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);
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/587ee4d3-cf8c-469e-93c3-174fa8be1d70/Untitled.png

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