Chapter 8. Repeating an Action with Loops

<feature><title></title>

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

</feature>

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. ...

Get Sams Teach Yourself Java™ in 24 Hours, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.