Page 160 - Introduction to Programming with Java: A Problem Solving Approach
P. 160
126 Chapter 4 Control Statements
The while loop body does just one thing—it prints 1 (since 0 1 is 1). It does not update x’s value (since there’s no assignment or increment statement for x). With no update for x, the while loop’s condi- tion(x < 10)alwaysevaluatestotrue.That’sanexampleofaninfiniteloop.Thecomputerexecutesthe statements in the loop body over and over—forever. When you have an infinite loop, the computer seems to freeze or “hang up.”
Insert tempo- rary print state- ments to see details.
Sometimes, what seems to be an infinite loop is just an extremely inefficient algo- rithm that takes a long time to finish. In either of these cases, you can figure out what’s happening by inserting into the loop a diagnostic statement that prints a value you think should be changing in a certain way. Then run the program and watch what happens to that value.
4.9 do Loop
Now let’s consider a second type of Java loop—the do loop. A do loop is appropriate when you’re sure that you want the loop body to be repeated at least one time. Because the do loop matches the way most com- puter hardware performs looping operations, it is slightly more efficient than the other types of loops. Un- fortunately, its awkwardness makes it prone to programming error, and therefore some programmers don’t like to use it. But at the very least, you need to be aware of it.
Syntax and Semantics
Figure 4.12 shows the do loop’s syntax and semantics. Note that the do loop’s condition is at the bottom. This contrasts with the while loop, where the condition is at the top. Having the condition tested at the bottom is how the do loop guarantees that the loop executes at least one time. Note the semicolon at the right of the condition. That’s required by the compiler, and omitting it is a common error. Finally, note that the while partisonthesamelineastheclosingbrace—that’sgoodstyle.It’spossibletoputwhile (<condition>); on the line after the closing brace, but that would be bad style because it would look like you’re trying to start a new while loop.
Apago PDF Enhancer
<statement(s)>
<condition> false
true
do
{
<statement(s)>
} while (<condition>);
Figure 4.12 Syntax and semantics for the do loop