What You’ll Learn in This Hour:
• Using the for
loop
• Using the while
loop
• Using the do
-while
loop
• 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. A loop is a statement or block that is repeated in a program. 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.
3.144.252.204