WEEK: 8
Active: February 28th - March 6th
Work Due: March 7th @ 9:00AM

while Loops

Another type of loop, very similar to for loops are while loops.

while loops;

  • do something
  • as long as, a conditional check function returns 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.

In Practice

while loops will be setup as follows;

  1. The keyword while
  2. Followed by a set of parentheses where a conditional statement will be evaluated.
  3. If the statement returns true then the function block of the loop is executed.
  4. At the end of the function blocks execution, the conditional statement is executed again. If it returns true again, then the function block is executed again.
  5. If instead the conditional statement returns 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.

An Example

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 ]

Previous section:
Next section: