While:
Just as with our conditional (if / else) statements a while loop employs boolean test that must evaluate to true in order for the instructions enclosed in the curly brackets to be executed. The difference is that the instructions continue to be executed until the test condition becomes false.
int x = 0;
while (x < 10)
{
println("x is less than 10.");
x++;
}
Consider doing a striped background. You could do the following:
void setup()
{
size(400,400);
background(128);
stroke(255,0,0);
strokeWeight(5);
}
void draw()
{
line(0,0,0,height);
line(20,0,20,height);
line(40,0,40,height);
// and so on..
// or you could use a variable:
int x = 60;
line(x,0,x,height);
x = x + 20;
line(x,0,x,height);
}
but that would get very tedious.
With a "while" loop we could do it much more quickly and easily:
void setup()
{
size(400,400);
background(128);
stroke(255,0,0);
strokeWeight(5);
}
void draw()
{
int x = 0;
while (x <= width)
{
line(x,0,x,height);
x = x + 20;
}
}
For Loop:
Since this is a common use of a loop (creating a variable, checking it's value and incrementing by a certain amount) there exists an even quicker way to do the above, all in one step.
for (int x = 0; x <= width; x = x + 20)
{
line(x,0,x,height);
}
You can read this as, create variable x and set it to 0, while x is less than or equal to the width, do the following. Increment x by 20 at the end.
Exactly what we are doing in the while loop but in one quick step.