Iteration

Resources:

Shiffman - 4.1 while and for Loops - p5.js
Shiffman - 4.2 Nested Loops - p5.js
p5 Examples: Iteration
p5 Examples: Embedded Iteration

for Loops

The for structure performs repetitive calculations and is structured like this:
for (init; test; update) {
      statements
}

The same result can be generated with fewer lines of code using a for loop:

The "update" value of the loop can be incremented using the arithmetic shortcuts we just learned:

The statements inside the loop can include conditional statements. Try modifying the conditions to get different results:

The modulus operator is often used within loops to create cycles:

Nested Iteration

The for structure produces repetitions in one dimension (or parameter). Nesting one of these structures into another compounds their effect, creating iteration in two dimensions.

The following code creates a one-dimensional array of points along the x dimension:

This code creates a one-dimensional array of points along the y dimension:

We can combine the above x and y loops into a nested loop. Instead of drawing 9 points and then drawing another 9 points, they combine to create 81 points; for each point drawn in the outer structure, 9 points are drawn in the inner structure.

The inner structure runs through a complete cycle for each single iteration of the outer structure. In the following examples, the two dimensions are translated into x-coordinates and y-coordinates:

Exercise 2.0: Nested Iteration

Create a new directory (folder) in your local repository called "exercise_2". Inside that folder, create an index.html and a script.js file. Within this file, use nested for loops to create a two-dimensional array of geometry. Use GitHub Desktop to commit and push your changes, and verify that they published to the web. This can be the basis for your Assignment 2.0: Tiles.