4.2 Programming with Loops

The cautious seldom err.

—CONFUCIUS

A loop typically involves three elements: the initializing statements that must precede any repetition, the loop body, and the mechanism for ending the loop. In this section we give you techniques for designing each of these loop components. Although the initializing statements come before the loop body, the loop body is naturally designed first, and so we will start our discussion there.

The Loop Body

One way to design a loop body is to write out the sequence of actions that you want your code to accomplish. For example, you might write the following actions:

  1. Display instructions to the user.

  2. Initialize variables.

  3. Read a number ...

Get Java: An Introduction to Problem Solving and Programming, 8th 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.