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:

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

In this case the alpha is based on the x co-ordinate. In the next example the blue component is also varied, but based on the y co-ordinate:

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

Clone this wiki locally