Artful Computing

Iteration is doing something over and over again. It is one of the most important ideas used in writing computer programs. Only the most trivial algorithms manage to avoid some element of iteration.

When you draw a repeating pattern, you are performing an iteration, reproducing the same motif over and over again. Of course, each iteration must be slightly different because there would be little point in drawing the motif exactly over itself again and again - so each time you move slightly this way or that way, or rotate things. Useful iterations therefore normally involve doing almost the same thing over and over, but with a little bit of difference every time.

In order to do any real job of work, you also always need to say how you are going to start and how you are going to finish. (It might be, for example: "Start at the left side of the paper, at each step draw the motif, then move 2 centimeters to the right, keep repeating until you run out of paper.")

One of the ways of iterating in Processing involves the "for" loop (this is taken from the Processing reference):

for (int i = 0; i < 80; i = i+5) {
  line(30, i, 80, i);
}

The starting condition is that the integer named i is set to zero, and has this value for the first execution of the instructions between the "{...}" brackets. The loop will continue iterating as long as i keeps below the value 80, but at the end of each loop i is incremented by 5.

It is convenient to use "for" loops when we know before we start the loop how many times we need to go round: writing it that way makes it very clear what is going on.

There is a different way of doing exactly the same thing using a "while" loop

int i = 0;
while (i < 80) {
  line(30, i, 80, i);
  i = i + 5;
} 

However, we are much more likely to use a "while" loop when we the condition that requires a finish is something that does not occur after a predictable number of cycles: it emerges from the calculation inside the loop. 

int noError = 0;
while (noError == 0) {                 // This loop will terminate if noError ever gets set to 1.
  noError = respond_to_user_request(); // noError gets set to 1 if any error occurs.

This is a very common pattern in programs that have to response interactively to user input: you keep doing what they want until it stops making sense!

Breadcrumbs