Section 6.9. Principles of Loop Design


[Page 277 (continued)]

6.9. Principles of Loop Design

Before moving on, it will be useful to summarize the main principles involved in correctly constructing a loop.

  • A counting loop can be used whenever you know in advance exactly how many iterations are needed. Java's for statement is an appropriate structure for coding a counting loop.

  • A while structure should be used when the problem suggests that the loop body may be skipped entirely. Java's while statement is specially designed for the while structure.

  • A do-while structure should be used only when a loop requires one or more iterations. Java's do-while statement is specially designed for the do-while structure.


  • [Page 278]
  • The loop variable is used to specify the loop-entry condition. It must be initialized to an appropriate initial value, and it must be updated on each iteration of the loop.

  • A loop's bound may be a count, a sentinel, or, more generally, a conditional bound. It must be correctly specified in the loop-entry expression, and progress toward the bound must be made in the updater.

  • An infinite loop may result if the initializer, loop-entry expression, or updater expression is not correctly specified.

The loop types are summarized in Table 6.1.

Table 6.1. Design decisions required when coding a loop

Use

If

Java Statement

Counting loop

Number of iterations known in advance

for

While structure

Number of iterations not known
Loop may not be entered at all

while

Do-while structure

Number of iterations not known
Loop must be entered at least once

do-while


Self-Study Exercise

Exercise 6.14

For each of the following problems, decide whether a counting loop structure, a while structure, or a do-while structure should be used, and write a pseudocode algorithm.

  • Print the names of all visitors to your Web site.

  • Validate that a number input by the user is positive.

  • Change all the backslashes (\) in a Windows Web page address to the slashes (/) used in a Unix Web page address.

  • Find the car with the best miles-per-gallon ratio among the cars in the Consumer Reports database.




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net