Hour 8. Repeating an Action with Loops

One of the more annoying punishments for schoolchildren is to make them write something over and over again on paper or a chalkboard. On The Simpsons, in one of his frequent trips to the board, Bart Simpson had to write, "I will not obey the voices in my head" dozens of times. This kind of punishment might work on children, but it definitely would fail to be punitive to a computer, which can repeat a task with ease. Computer programs are ideally suited to do the same thing over and over again because of loops. A loop is a statement or set of statements that will be repeated in a program. Some loops take place a fixed number of times. Others take place indefinitely. There are three loop statements in Java: for, do, and while. These statements are often interchangeable in a program because each can be made to work like the others. The choice to use a loop statement in a program often depends on personal preference, but it's beneficial to learn how all three work. You frequently can simplify a loop section of a program by choosing the right statement. The following topics will be covered during this hour:

  • Using the for loop
  • Using the while loop
  • Using the do-while loop
  • Exiting a loop prematurely
  • Naming a loop
      
Comments