Iteration: the for-loop

Another structure to control a sequence of repetitions is the for-loop:



* When for() begins, it executes the init statement ONCE. Then, it checks the condition.

*If the condition is true, the code inside the {} is executed. Afterwards, the update statement is executed and for() returns to check the condition. While the condition is true, for() follows the same procedure.

*When the condition is false, the program continues with the next statement after the }


for (my_var=1;my_var<5;my_var=my_var+1) {
//how many times will this execute?


//you can declare a counter i particularly for the for-loop
for (int i=0;i<5;i++) {
// i doesn't have to start from 0 but counting in programming tends to start from 0 and not from 1
// i "lives" only within the for-loop


//let's draw 20, 50, 100, ... random ellipses
int num= 20;
for(int i=0; i<num; i++) {
fill(random(255), 0, random(255), 100);
ellipse(random(width), random(height), 30,30);

Your browser does not support the canvas element Your browser does not support the canvas element

[More examples...]

for (int i=0;i<5;i++) {
//this counter starts from 0: 0,1,2,3,4, stops at 5
for (int i=1;i<5;i++) {
//this counter starts from 1, how many times will the for-body execute?
for (int i=1;i<=5;i++) {
//this counter starts also from 1, but there is a small difference
for (int i=0;i<100;i+=50) {
//you do not have to increase only by one
for (int i=5;i>0;i--) {
//and you don't have to only increase either