The for Loop Statement

We will turn to the last loop statement: the for statement.  

bullet

Syntax: The for loop has the following form.

 

for ( initialization; boolean-condition; update)

loop-body //a statement or  a block

 
bulletImportant Notes: 
bulletSimilar to the while loop, the for loop is a pre-test loop.
bulletBecause it is a pre-test loop, the for loop is a "minimum of zero" loop.

bulletAdvantage of for loop: Any for loop is equivalent to some while loop, so the language doesn't get any additional power by having the for statement.  
bulletFor certain type of problem, a for loop can be easier to construct and easier to read than the corresponding while loop. 
bulletThe for statement makes a common type of while loop easier to write. 
bulletIt is a very good (perhaps the best) choice for counting loops.

 

bulletWriting a while loop as a for loop:
bulletThe while loop has the following general form:
initialization
while ( continuation-condition ) {
  statements
  update
}
Consider the following example,
int x = 1;  // initialize the variable x
while ( x < 10 ) {   // condition for continuing loop

    System.out.println(" x = " + x);
    x++;   // update the value of x

}

This loop can be written as the following equivalent for statement:

for ( x = 1;  x < 10;  x++ ) {
  System.out.println(" x = " + x);
}

The initialization, continuation condition, and updating have all been combined in the first line of the for loop. Keeping everything involved in the "control" of the loop in one place makes the loop easier to read and understand. 

The for loop is executed in exactly the same way as the original code: The initialization part is executed once, before the loop begins. The termination condition is evaluated before each iteration, and the loop ends when this condition is false. The update part is executed at the end of each iteration, just before the next iteration.

bulletUsing for loop as counting loop: The most common type of for loop is the counting loop, where a loop control variable takes on all integer values between some minimum and some maximum value. Such counting loop has the form:
for ( variable = min; variable <= max; variable++ ) {

  //loop body

}
 
bullet The break Statement