Top-driven Loop

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:

The output is:

0 1 2 3 4 5
sum is 15

Top-driven Loop

Here is the example for loop and its equivalent while loop:

for loop   while loop
int count, sum;
sum = 0;

for ( count = 0; count <= 5; count++ )
{
  sum = sum + count ;
  System.out.print( count + " " );
}

System.out.println( "sum is: " + sum );
 
int count, sum;
sum   = 0;
count = 0;

while ( count <= 5 )
{
  sum = sum + count ;
  System.out.print( count + " " );
  count++ ;
}

System.out.println( "sum is: " + sum );

Notice two important aspects of these loops:

  1. The test is performed every time, just before execution is about to enter the loop body.
  2. The change is performed at the bottom of the loop body, just before the test is re-evaluated.

Loops that work this way are called top-driven loops, and are usually mentally easier to deal with than other arrangements. Look back at the loop flow chart to see this graphically.

QUESTION 5:

Where should the initialization part of a loop be located in order to make it mentally easy to deal with?