Most of us find that doing the same thing over and over and over again gets to be boring rather rapidly. Fortunately, computer's don't feel this way. This is fortunate because repetition is the only way we have any hope of exploiting the power of a computer. As we discussed in the first class, part of the computer's power comes from the fact that it can follow the instructions stored within its memory rapidly without waiting for a human being to press a button or flip a switch. In all of the examples we have considered, the sequences of instructions preformed when we do click are quite short and then the computer has to wait for us again. We could get more work out of the the computer by writng methods that were thousands of lines long, but this would be painful. There is only one choice left. The only way to get the computer to execute thousands or millions of instructions without having written thousands or millions of instructions ourselves is to have the computer execute the same instructions over and over and over again. At first, this may seem like a boring and inefficient use of the computer.
In fact, when in comes to following instructions, doing the same thing over and over again can be very interesting. Think of the scribble program or the Spirograph program. Each time we drag the mouse in these programs, the computer "does the same thing" in the sense that it executes the same instructions -- the body of onMouseDrag. Each time these instructions are executed, however, the computer actually does something different because the meaning of at least one of the variables referenced in the instructions, point, has changed.
Demo: click to display a circle; repeat.
| where | left | top |
| begin | 10 | 10 |
| onMouseClick | 50 | 40 |
| onMouseClick | 90 | 70 |
| ... | ||
| onMouseClick | 370 | 280 |
| onMouseClick | 410 | 310 |
Demo: click once for all circles to appear.
The syntax of a while statement is:
while (condition)
{
...
}
As in the if statement, the condition used in a while must be some expression that produces a boolean value. The statements between the open and closed curly brackets are known as the body of the loop.
A common way the while loop is used is as follows:
while (condition)
{
do something
change some variable so that next time you do something a bit differently
}
Demo: click once for a curving bunch of circles.
Demo: click once for a bunch of bouncing circles
Demo: click once for a bunch of circles that fill the canvas.