6.1 – Nested For Loops

You can use a loop inside of a loop to create columns and rows. Lets start by look at this logic with WHILE loops:

void setup() {
  size(400, 400);
}

void draw() {
  background(255);
  int x = 10;
  while (x <= width){
   int y = 10;
   while(y <= height){
    fill(0);
   rect(x, y, 20,20);
    y += 30;
   } 
   x += 30;
  }
}

The first time we go enter the x while loop, x is equal to 10. Then we jump into our second while loop where x is still equal to 10 and y is equal to 10. We draw our first ellipse at (10,10) and then we add 30 to y and loop back up to our y while loop. Since y is less than height (now it’s 40), it passes the boolean test of y <= height, so we create another ellipse at (10, 40). We repeat this process until y becomes greater than height (we reach the end of the column), then we break out of our y while loop, but we’re still inside of our x loop! So now we had 30 to x and start back at the top of our x while loop. It passes the boolean test of x <= width, so then we reset the variable y back to 10 (if we didn’t, y would be greater than height and wouldn’t pass the boolean test of the y while loop, meaning we’d only draw one column). Now we draw an ellipse at (40, 10), we add 30 to y, hop back through our y while loop until y becomes greater than height (aka, we finish row 2), and we repeat this process until both x and y are greater than width and heigh respectively.

We can do the exact same thing with nested FOR loops. The logic here is exactly the same, we’re just condensing our code by writing our variable declaration, test/exit strategy, and increment/decrement in one line of code.

void setup(){
size(400,400);
}

void draw(){
background(255);
for(int x = 10; x<= width; x+=30){
    for(int y = 10; y<= height; y+=30){
    fill(0);
    rect(x,y,20,20);
  }
 }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *