Just as with conditional (if /else ) structures, a while loop employs a boolean test condition. If the test evaluates to true, the instructions enclosed in curly brackets are executed; if it is false, we continue on to the next line of code. The difference here is that the instructions inside the while block continue to be executed over and over again until the test condition becomes false.int x = 0;
The for loop is a nifty shortcut for commonly occurring while loops. Before we get into the details, let’s talk through some common loops you might write in Processing and how they are written as a for loop.
:Here, a variable is declared and initialized for use within the body of the loop. This variable is most often used inside the loop as a counter.
: This is exactly the same as the boolean tests found in conditional statements and while loops. It can be any expression that evaluates to true or false.
: The last element is an instruction that you want to happen with each loop cycle. Note that the instruction is executed at the end of each cycle through the loop
B. Local vs. Global Variables (AKA “ Variable Scope ” )
Up until this moment, any time that we have used a variable, we have declared it at the top of our program above setup( ).At this point, we need to know the concept of variables’ scope
Global variables,which exist (i.e., are accessible) throughout the entire course of a program’s life, Local Variables which live temporarily, only for the brief moment when their value is required for an instruction or calculation. In Processing , global variables are declared at the top of the program, outside of both setup( ) and draw( ) .These variables can be used in any line of code anywhere in the program. This is the easiest way to use a variable since you do not have to remember when you can and cannot use that variable.
Local variables are variables declared within a block of code. So far, we have seen many different examples of blocks of code: setup( ) , draw( ), mousePressed( ) , and keyPressed( ), if statements,and while and for loops…. A local variable declared within a block of code is only available for use inside that specific block of code where it was declared.
A for loop offers up a spot for a local variable within the “ initialization ” part: