您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
                                   Content Page # 7

Iteration: FOR

Aforstatement works in a very similar way to an whilestatement. However, forstatements 
are particularly useful for concisely writing counter controlled loops.

The general form of aforstatement can be illustrated as:

for( <loop initialise>; <loop condition>; <post loop action>)
{
  <actions to perform if loop condition is true>
     }

The way aforloop works is as follows:

  • first the <loop initialise> statement is executed
  • then the loop condition is tested
  • if the loop condition is true
  • the loop actions are performed
  • the post loop action is performed
  • the loop condition is tested again and so on
  • once the loop condition is found to be false, the loop terminates
An example of awhile loop, and its equivalent for loop are as follows:
    // a WHILE loop

    int counter = 0;

    while( counter < 10 )
    {
      <action1>
      <action2>
      counter = counter + 1;
    }

    // an equivalent FOR loop

    int counter;

    for( counter = 0; counter < 10; counter = counter + 1)
    {
      <action1>
      <action2>
    }

As can be seen, for counter controlled loops such as the above, the for loop is neater, since it moves the post loop action of incrementing the counter inside the loop definition line.

The table below illustrates what happens when this for loop is executed:

     

    As the for loop iterates the following happens:

    counter loop condition
    <action1>
    <action2>
     
    post loop action: counter = counter + 1
     
    0
    0 < 10 = true
     
    actions 1 and 2 are executed
    counter= 0 + 1 = 1
     
    1
    1 < 10 = true
     
    actions 1 and 2 are executed
    counter = 1 + 1 = 2
     
    2     2 < 10 = true actions 1 and 2 are executed
    counter = 2 + 1 = 3
     
    3
    3 < 10 = true
     
    actions 1 and 2 are executed
    counter = 3 + 1= 4
     
    ... ... < 10 actions 1 and 2 are executed counter = counter + 1
    9
    9 <10 = true
     
     
    actions 1 and 2 are executed
    counter         = 9 + 1= 10
     
    10  
    10 < 10= false
    loop terminates 
     
Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg