Wednesday, August 27, 2014

The for Repetition Structure

The for repetition structure handles all of the details of counter-controlled repetition. The first line is sometimes called the for structure header. Notice that the for structure "does it all": It specifies each of the items needed for counter-controlled repetition  with a control variable. If there is more than one statement in the body of the for structures, braces ( { and } ) are required to define the body of the loop.

for ( int counter=1; counter <= 10; counter++ )

where:

  1. for is a keyword
  2. counter is the control variable
  3. 1 is the initial value of control variable
  4. 10 is the final value of control variable
  5. counter <= 10 is the loop-continuation condition
  6. counter++ is the increment of control variable

The general format of the for structure is
  
  for (expression1; expression2; expression3 )
        statement

where expression1 names the loop's control variable and provides its initial value, expression2 is the loop-continuation condition (containing the control variable's final value) and expression3 modifies the value of the control variable, so that the loop-continuation condition eventually becomes false. In most cases, the for structure can be represented with an equivalent while structure, with expression1, expression2 and expression3 placed as follows:

expression1;
while ( expression2 ) {
   statement;
   expression3;
}

No comments:

Post a Comment