ptg7068951
WHAT YOU’LL LEARN IN
THIS HOUR:
.Using the forloop
.Using the whileloop
.Using the do-whileloop
.Exiting a loop prematurely
.Naming a loop
One of the more annoying punishments for schoolchildren is to make them
write something over and over again on a chalkboard. On The Simpsons, in
one of his frequent trips to the board, Bart Simpson had to write, “The art
teacher is fat, not pregnant,” dozens of times. This punishment might work
on children, but a computer can repeat a task with ease.
Computer programs are ideally suited to do the same thing over and over
because of loops. Aloopis a statement or block that is repeated in a pro-
gram. Some loops run a fixed number of times. Others run indefinitely.
There are three loop statements in Java: for, do, and while. Each can work
like the others, but it’s beneficial to learn how all three operate. You often
can simplify a loop section of a program by choosing the right statement.
for Loops
In your programming, you find many circumstances in which a loop is
useful. You can use them to keep doing something several times, such as
an antivirus program that opens each new email received to look for virus-
es. You also can use loops to cause the computer to do nothing for a brief
period, such as an animated clock that displays the current time once per
minute.
A loop statement causes a computer program to return to the same place
more than once, like a stunt plane completing an acrobatic loop.
Java’s most complex loop statement is for. Aforloop repeats a section of
a program a fixed number of times. The following is an example:
HOUR 8
Repeating an Action with Loops