Completion requirements
The 'for' loop is more compact than the 'while' and 'do' loops and automatically updates the loop counter at the end of each iteration. Both 'for' and 'while' loops are designed for different situations. You'll learn more about when to use each later.
11. Omitting Parts of the for
Answer:
No. In more complicated expressions using a postfix operator instead of a prefix operator usually
makes a difference, but not here.
Omitting Parts of the for
for
for loop
|
while loop
|
---|---|
for ( initialize ; test ; change ) loopBody ; |
initialize; while ( test ) { loopBody; change } |
Parts of a for
can be omitted. Since the three parts of a for
are the three parts of any loop, when a part is eliminated from a for
it has to be done elsewhere. Recall that
the
for
is equivalent to a while
.
You can omit the initialize part from the for
loop. It now acts the same as a while
loop with its initialize part omitted. Doing this is useful when initialization is complicated
and you wish to do it in several statements before the loop. For example, initialization may depend on user input:
// 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);
Question 11:
Do you think that the change part of a for
can be omitted (as long as it is done somewhere else)?