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.

4. Any Kind of Loop


Answer:

    for ( count = 0; count < 10; count++ ) System.out.print( count + " " );

Outputs:

    0 1 2 3 4 5 6 7 8 9

Any Kind of Loop

Although the previous example is a counting loop, the for statement can be used to implement any of the three types of loops. The three parts, initializetest, and change can be as complicated as you want.

Here is a for loop with several statements in the loop body:

int count, sum;

sum = 0;
for ( count = 0; count <= 5; count++ )
{
sum = sum + count ;
System.out.print( count + " " );
}
System.out.println( "\nsum is: " + sum );

Since the loop body consists of several statements, they are enclosed in braces { and } to make a block.


Question 4:

What is the output of this new loop? Pay careful attention to the test part of the loop.