## The For Statement

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.

### 5. Top-driven Loop

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 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?