The output is:
0 1 2 3 4 5 sum is 15
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:
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.
Where should the initialization part of a loop be located in order to make it mentally easy to deal with?