Iteration (for loops)



Draw a vertical line. Now draw two parallel, now three…

Introducing for loops:

for (var i=1; i<=10; i++)
{
print(i);
}

This draws 10 horizontal lines:

for (var i=1; i<=10; i++)
{
line (10, i*10, width, i*10);
}

Change the color gradually using the counter i!
Generalize the formula using variables for the distance and the number of lines!

There can be multiple instructions in the same loop:

for (var i=0; i<50; i++)
{
line (0, i*10, width, i*10);
ellipse(10*i, i*10, 10, 10);
}

Make a more complex pattern using at least 3 for loops or multiple instructions in the same loop!

You can add randomness to the order:

for (var i=0;  i<50; i++)
{
line (0, i*10, width, i*10);
float posX = random(0, width);
ellipse(posX, i*10, 10, 10);
}

Create a composition with 12 randomly generated shapes, using iteration!

<h1>Embedded iteration</h1>

What if you have to iterate on two dimensions?
This is a tiling example using indexes as coordinates.

function setup()
{
background(0);
stroke(18, 255, 233);

for (var x = 0; x &lt;= width; x += 20) {
for (var y = 0; y &lt;= height; y+=20) {
rect(x, y, 10, 10);
}
}
}

This is an example using indexes as number of rows and columns.

In this way you have better control over the number of shapes that are being drawn.

var rows = 8;
var cols = 12;
var circleDiameter = 40;
var distanceX = 30;
var distanceY = 30;

function setup()
{
createCanvas(400,300);
background(0);
stroke(18, 255, 233);

for (var r = 1; r<= rows; r++) {
for (var c = 1; c <= cols; c++) {
ellipse(c*distanceX, r*distanceY, circleDiameter, circleDiameter);
}
}
}

You can control other parameters too:

var box_size = 11;
var box_space = 12;
var margin = 7;

function setup()
{
createCanvas(200, 200);
background(0);
noStroke();

// Draw gray boxes

for (var i = margin; i<height-margin; i += box_space){
if(box_size &gt; 0){
for(var j = margin; j<width-margin; j+= box_space){
fill(255-box_size*10);
rect(j, i, box_size, box_size);
}
box_size = box_size - 0.6;
}
}

<h1>While loop</h1>
Sometimes you don’t know in advance how many times you want to iterate and/or you don’t need an loop counter (variable i). In these cases while loops can be handy. Make sure you exit condition is met at some point:

function setup()
{
createCanvas(200,200);
background(255);
noStroke();

var w = width;

while (w > 0) {
fill(w);
ellipse(width/2,height/2,w,w);
w = w - 20;
}

Posted in