Java Reference
In-Depth Information
if (maximum < x) maximum = x;
H OW T O 6.1: Implementing Loops
You write a loop because your program needs to repeat an action multiple times.
As you have seen in this chapter, there are several loop types, and it isn't always
obvious how to structure loop statements. This How To walks you through the
thought process that is involved when programming a loop.
Step 1 List the work that needs to be done in every step of the loop body.
For example, suppose you need to read in input values in gallons and convert them
to liters until the end of input is reached. Then the operations are:
ȗ
Read input.
ȗ
Convert the input to liters.
ȗ
Print out the response.
Suppose you need to scan through the characters of a string and count the vowels.
Then the operations are:
ȗ
Get the next character.
ȗ
If it's a vowel, increase a counter.
Step 2 Find out how often the loop is repeated.
Typical answers might be:
ȗ
Ten times
ȗ
Once for each character in the string
ȗ
Until the end of input is reached
ȗ
While the balance is less than the target balance
If a loop is executed for a definite number of times, a for loop is usually
appropriate. The first two answers above lead to for loops, such as
Search WWH ::




Custom Search