Skip to content

Nested loops

Jolon Faichney edited this page Feb 16, 2017 · 2 revisions

We can place a loop inside of another.

This example lays out a 2D grid of ellipses:

for (var i = 0; i < 5; i++) {
    for (var j = 0; j < 6; j++) {
        ellipse(i * 100 + 50, j * 25 + 30, 55, 55);
    }
}

We can see that there is a loop inside of a loop, we call this a nested loop. The outer loop is for the x axis, each time through the loop we go to the next column on the x axis. Inside the loop we have another loop which is for the y axis. Each time through the y axis loop we go down a row.

Therefore the ellipses are drawn firstly down the first column, and once that has finished, returns to start the next column.

In this example we have used the variable name j for the inner loop. It is common to use variable names i, j, and k for loops. However, x and y could also be used.

We can go a step further and also adjust the colour:

Clone this wiki locally