|
Would the output of the program be any different if the expression
A good answer might be:No. In more complicated expressions it might make a difference, but not here. | ||||||
Omitting Parts of the |
| for loop | == | while loop |
|---|---|---|
for ( initialize ; test ; change ) loopBody ; |
initialize
while ( test )
{
loopBody
change
}
|
If you eliminate the initialize from the for it is
as if you eliminated it from the equivalent while.
This is useful when initialization is complicated and you wish to
do it in several statements before the loop.
For example:
// get initial value of count from the user here
for ( ; count < 13; count++ )
{
System.out.println( "count is: " + count );
}
System.out.println( "\nDone with the loop.\nCount is now" + count);
Do you think that the change part of a for can be omitted
(as long as it is done somewhere else)?