Iteration: the while-loop

Very often, it is useful to have actions performed repeatedly: e.g. in order to reproduce a similar shape multiple times or when you want to perform similar calculations multiple times. You can control a sequence of repetitions by using loops.

A loop is a set of statements (actions) that execute continuously depending on a condition (test)

 

while

* If the condition is true, the code inside the {} is executed. Afterwards, the program returns to the entry point of the loop to check again the condition. In fact, the code inside the {} will be executed while (as long as) the condition is true.

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

*IMPORTANT: the code inside the {} needs to update the condition for the loop to terminate

Examples

int my_var=1;
while (my_var<5) {
println("hello!");
my_var=my_var+1; //always update the variable used in the condition

}
//what will this do for my_var=1, my_var= 4, my_var=5?

--------------------------------------------------

//an infinite loop - definitely a no-no
int my_var=1;
while (my_var<5) {
println("hello!");
}
//what will this do for my_var=1, my_var=4, my_var=5?
//NEVER use a while() as an if()

--------------------------------------------------

//a slightly more useful loop
int my_var=1;
while (my_var<5) {
println("hello:"+my_var); // print a changing message
my_var=my_var+1; //update the variable used in the condition
}
//what will this do for my_var=1, my_var=4, my_var=5?

Note

Do not confuse repetition within a loop with the repetition of draw() in continuous programming mode. A loop is the compact equivalent of a long list of statements, you can use loops already in the basic programming mode. In the continuous programming mode, your loop completes within a single frame and it is only because of draw() that code repeats over time.