Java Reference
In-Depth Information
loopVar = 0;
External initialization
while(loopVar != 10)
Loop continuation test
{
// Processing statements
loopVar++;
Loop variable update
}
Figure10-3ElementsofthewhileLoopConstruct
Programmersnote:
Thewhileloopevaluatesthetestexpressionbeforetheloopstate-
mentblockexecutes.ForthisreasontheAsciiCodesprogram,listed
previously,displaysthevaluesbetween0x10and0x20,butnot0x20.
Thismodeofoperationisconsistentwiththemeaningoftheword
while.
Do-While Loop
Acharacteristicofthewhileloopisthatifthetestconditionisinitially
false,theloopneverexecutes.Forexample,thewhileloopinthefollowing
codefragmentwillnotexecutethestatementbodybecausethevariable x
evaluatesto0beforethefirstiteration
intx=0;
...
while (x != 0)
System.out.println(x);
Inthedo-whileloop,thetestexpressionisevaluatedaftertheloopex-
ecutes.Thisensuresthattheloopexecutesatleastonce,asinthefollow-
ingexample:
intx=0;
...
do
System.out.println(x);
while (x != 0);
Inthecaseofthedo-whileloop,thefirstiterationalwaystakesplace
becausethetestisnotperformeduntilaftertheloopbodyexecutes. Fig-
ure10-4 showstheelementsofthedo-whileloop.
 
Search WWH ::




Custom Search