Omitting Parts of the for

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

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

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 made up elsewhere. Recall that the for is equivalent to a while:

for loop while loop
for ( initialize ; test ; change )
  loopBody ;
initialize;
while ( test )
{
  loopBody;
  
  change
}

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);

Here is a Javascript simulation of this:



Enter initial value for count:

QUESTION 11:

Do you think that the change part of a for can be omitted (as long as it is done somewhere else)?