Skip to main content

Section 5.2 Indefinite Loops

Both Python and Java support the while loop, which continues to execute as long as a condition is true. Listingย 5.2.1 shows a simple example in Python that counts down from 5.
Listing 5.2.1.
In Java, we add parentheses and curly braces. Listingย 5.2.2 shows the same countdown loop in Java.
Listing 5.2.2.
Java adds an additional, if seldom used variation of the while loop called the do-while loop. The do-while loop is very similar to while except that the condition is evaluated at the end of the loop rather than the beginning. This ensures that a loop will be executed at least one time. Some programmers prefer this loop in some situations because it avoids an additional assignment prior to the loop. For example, Listingย 5.2.3 shows how loop will execute once even though the condition is initially false.
Listing 5.2.3.

Checkpoint 5.2.4.

Rearrange the blocks to create a Java method that accepts a starting balance and a target amount, then calculates how many years it takes for the balance to reach or exceed the target by doubling each year.
You have attempted of activities on this page.