6.9: Principles of Loop Design

Java, Java, Java - Object-Oriented Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    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.
    • 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 Table 6.1.

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

    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

    Exercise \(\PageIndex{1}\)

    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.

     


    This page titled 6.9: Principles of Loop Design was last modified on Thu, 23 Apr 2026 23:41:38 GMT and is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli and Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform.