xxxxxxxxxx
47
/* Loops
There are a couple of different kinds of loop structures in JavaScript, but a 'for loop' is by far the most popular
For Loops have 4 parts: example for loop
for (let i=0; i<10; i=i+){
//do something
}
FIRST we initialize a variable to keep track of the number = lets call this a counter variable
let i=0;
Inside loops we tend to use short variable names such as i or j if they are just controlling the 'flow' of the loop.
SECOND we define the test condition for the loop, this gets evaluated (tested ) each time the loop is about to start. Our example we are testing if our counter variable is smallet than 10
i < 10;
THIRD we are (defining a way ) updating the counter variable that then gets evaluated at the end of the loop. We are getting the current value of the variable i and adding 1 to it.
i = i + 1;
FORTH, final part, is inside the { } we write the code that the we want repeated. Once the variable counter doesn't 'satisfy' the test i<10 the loop terminates.
*/
function setup() {
createCanvas(500, 300);
}
function draw() {
background(1,75,220);
// circle properties
fill(237, 34, 93);
noStroke();
let diameter = 35;
for(let i=0; i<width/diameter; i=i+1){
ellipse(diameter/2 +i * diameter,30,diameter,diameter);
// we use the variable values instead of hard coding the numbers. It means we can just update / modify the variable diameter to change the out of the code
}
}