Loops and array indexes

There are three different kinds of loops than you can make in a sketch:

  1. the draw function,
  2. for loops,
  3. while loops

The draw function should exist in almost all sketches. It automatically loops - this function is called over and over again while the sketch is running. This is the basis for most animations because the draw function usually draws pictures that change each time through the loop. In the example below, I have used the draw function to display the contents of an array one at a time, always in the same place, and the canvas background is cleared each time. To make a different array element appear each time through the draw function, I have created an index variable "counter" that starts at 0 and gets one bigger each time the draw function is called. I also had to check if the value becomes bigger than the size of the arry and reset it back to 0.

Next, the example shows a "for" loop. This kind of loop repeats many times very quickly - so quickly that the results appear in an instant. In my example, I have printed out all the elements of the array at different places across the canvas. For loops must have an index built into them that starts at a particular value and ends at a different value, with some method of changing the index each time. All three of these things are built into the first line of the "for" statement. Then there is a section of code that is repeated. It is useful to make use of the index variable in this code so that each time through the loop does something slightly different.

Source code for the sketch