next up previous
Next: Arrays: Giving your Loop Up: Loops Previous: whileing Away Time: Some

forever And A Day: Knowing In Advance

So what can we do when we know in advance how many times we're going to execute the loop? We can use an abbreviation for the while loop called the for loop. Everything that can be done with the for loop can be done with the while loop: the for loop is a special case of the while loop.

This is what a for loop looks like:


int n=3;
int i;
for(i = 0; i < n; i++){

// statements to be executed on each pass through the loop

}

and it is equivalent to the following while loop:


int n = 3;
int i = 0;
while (i < n) {

// block of code to be executed

i++;
}

Note that the i = 0 assignment in the while loop gets moved into the for statement, the i < n expression remains the same, and the statement to increment i (i++) is also put into the for statement, but it is as if it gets executed at the end of the block. That is, in the for statement, we have no control over where the third statement gets executed -- it is the statement that gets executed immediately before control reaches the end of the block and jumps to the top again.

Notice also that in spite of the fact that control jumps to the top after reaching the bottom of the block of the for statement, the initialization i = 0 occurs only once (the first time that control encounters the for statement), while the comparison i < n happens each time control reaches the for statement. So the first time the line for(i = 0; i < n; i++) is reached, i=0 is executed, then the expression i < n is evaluated. If it is true, then the block of code is executed; false then control jumps to the statement immediately following the block. If it was true and the block was executed, then i++ is executed, then control jumps to the top of the for loop where i < n is evaluated, and the situation repeats. i = 0 is never executed after the first time.

Note that the for statement has the general form:

for( FOR_INIT, EXPRESSION, FOR_UPDATE) where

  1. FOR_INIT can be a comma delimited list of local variable declaration, assignment, increment/decrement, method invocation, and/or class instantiation statements
  2. EXPRESSION must be a boolean valued expression
  3. FOR_UPDATE can also be a comma delimited list of statements as FOR_INIT, but no variable declarations are allowed here

Having said this, most of the time you'll want to use i = 0 or int i = 0 for FOR_INIT, and something like i++ or i-- or i += 7 or some such thing for FOR_UPDATE.

For an exercise, try writing a method which takes a String as a parameter, and returns a String, where the returned string is in reverse order. Use a loop of some kind in your method.


next up previous
Next: Arrays: Giving your Loop Up: Loops Previous: whileing Away Time: Some
Chris Trendall
Copyright ©Chris Trendall, 2001. All rights reserved.

2001-12-09