For Loops

This lesson will look at a special type of while loop called a for loop.

Initialize, test, increment

Looking back at the previous lesson, we created a while loop that made a bunch of equally spaced circles on a canvas.

function setup(){
  createCanvas(260,260);
  background(220);

  var y = width/2;
  var d = 35;
  var spacing = 60;

  var x = 20;
  while(x < width){
    ellipse(x,y,d,d);
    x += spacing;
  }
}

Let’s take a second to examine the structure that we used. First, we initialized a variable, in this case x. Next we started our loop by testing if the boolean expression was true or false. then we ran some code and before we finished the loop we incremented our variable that we initialized at the start.

var x = 20;             //initialize
while(x < width){       //test
    ellipse(x,y,d,d);
    x += spacing;       //increment
}  

This is such a common type of while loop that they made a special loop, called a for loop, just for this case.

How to write a for loop.

The way that a for loop works is that it combines all three of those steps from above—initialize, test, increment—inside of the parentheses (). To make things easy to understand, each step is separated by a ; So in general we’ll have

for(initialize, test, increment){
  //do this
}

For our code above we can rewrite our for loop as:

for(var x = 20; x < width; x += spacing){
  ellipse(x, y, d, d);
}

This code operates exactly the same way as the while loop that we wrote in the last lesson.

Video Explanation

Comprehension Check

Assignment

Translate your code from 04-01 using for loops, instead of a while loop.

Write a sketch that uses ‘for’ loops to create two opposing diagonals of circles on the canvas such that they make an “X” with each diagonal sharing a central circle.


Previous section:
Next section: