Another type of loop, very similar to for loops are while loops.
while loops;
true
.As just mentioned while loops are very similar to for loops. For loops tend to be used when there is some value, that will be incremented/decremented in some way, with a specific measurable end in relation to the updating value.
while loops tend to be used when there is some condition that will change in the course of the loop, but is not necessarily incremental based or the number of executions needed is known.
while loops will be setup as follows;
while
true
then the function block of the loop is executed.true
again, then the function block is executed again.false
, then the loop is exited.// while loop syntax example
while( conditionStatement ) {
// function block to do something
}
One of the things to be careful when composing while loops is to ensure that they will eventually exit.
In the following example, the while loop is used to create a random number of dots, placed on a grid, with 50px spacing. The while loops checks the variable x
each iteration to see if it equals 0. If it does, then the while loops exits, and the draw()
starts all over again.
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |