Iteration (for loops)


Introducing for loops:

for (int i=1; i< =10; i++)
  {
  println(i);
  }

This draws 10 horizontal lines:

for (int 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 (int 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 (int i=0; 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!

Embedded iteration

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

 
size(500, 500);
smooth();
noFill();
 
background(0);
stroke(18, 255, 233);
 
 for (int x = 0; x <= width; x += 20) {
      for (int y = 0; y <= 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.

size(400, 300);
smooth();
noFill();
 
background(0);
stroke(18, 255, 233);
 
int rows = 8;
int cols = 12;
int circleDiameter = 40;
int distanceX = 30;
int distanceY = 30;
 
for (int r = 1; r <= rows; r++) {
  for (int c = 1; c <= cols; c++) {
 
    ellipse(c*distanceX, r*distanceY, circleDiameter, circleDiameter);
  }
}

Iteration can control other parameters too:

float box_size = 11;
float box_space = 12;
int margin = 7; 
 
size(200, 200);
background(0);
noStroke(); 
 
// Draw gray boxes 
 
for (int i = margin; i < height-margin; i += box_space){
  if(box_size > 0){
    for(int 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;
  }
}

While loop

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:

size(200,200); 
background(255); 
noStroke();
smooth();
 
float w = width; 
while (w > 0) { 
  fill(w); 
  ellipse(width/2,height/2,w,w); 
  w = w - 20; 
}
Posted in

Post a comment