Interaction Design WikiProgramming

p5.js Loops

A loop is a control statement that allows us to repeat a code block. Loops contain a conditional which determines how many times the code block is repeated.

There are few different loop types:


For-loop

The for loop loops through a block of code a specified number of times.

for([variable declaration], [condition], [increment step]) {

[code block] 

}

for(let i=0; i <= 100; i++)
{
   print(i);
}

For-In-loop

The for in loop loops through the properties of an object.

for([variable declaration], [condition], [increment step]) {

[code block] 

}

let person = {name:"Maik", surname:"Muster"};
let x;

for (x in person) {
      print(x)
 }

While-loop

The while loop cycles through a block of code as long as its specified condition is true.

while ([condition]) {

 [code block]
}

let x=0;
while(x <= 100)
{
   print(x);
   x++;
}

Do-While-loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, it will then repeat the loop as long as the condition is true.

do{
} while([condition]);

let x=0;

do
{
   print(x);
   x++;
} while(x <= 100);

Exercise

Write a program that creates a line of animated icons on the screen using a loop. Make use of the sin() function to create a simple oscillation.