4.6. Nested Loops

 
[Page 104 ( continued )]

4.5. Which Loop to Use?

The while loop and for loop are called pre-test loops because the continuation condition is checked before the loop body is executed. The do-while loop is called a post-test loop because the condition is checked after the loop body is executed. The three forms of loop statements, while , do-while , and for , are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (a) in the following figure can always be converted into the for loop in (b):

A for loop in (a) in the next figure can generally be converted into the while loop in (b) except in certain special cases (see Review Question 4.12 for such a case):

Use the loop statement that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message a hundred times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is . A do-while loop can be used to replace a while loop if the loop body has to be executed before the continuation condition is tested .

Caution

Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below in (a). In (a), the semicolon signifies the end of the loop prematurely. The loop body is actually empty, as shown in (b). (a) and (b) are equivalent.


[Page 105]

Similarly, the loop in (c) is also wrong. (c) is equivalent to (d).

These errors often occur when you use the next-line block style.

In the case of the do-while loop, the semicolon is needed to end the loop.


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

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