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.
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 also summarized in the table below.
Table6.9.1.A summary of the 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
while
Loop may not be entered at all
Do-while structure
Number of iterations not known
do-while
Loop must be entered at least once
ExercisesSelf-Study Exercise
1.Loop Choices.
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 (\(\backslash\)) 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.