Skip to main content
Lesson 10 - for, do-while, Nested Loops
ZIPPDF (letter)
Lesson MenuPreviousNext
  
The for Loop page 3 of 10

  1. The for loop has the same effect as a while loop, but using a different format. The general form of a for loop is:

    for (statement1; expression2; statement3)  
      statement

    statement1 initializes a value
    expression2 is a boolean expression
    statement3 alters the key value, usually via an increment/decrement statement

  2. Here is an example of a for loop, used to print the integers 1-10.

    for (int loop = 1;  loop <= 10;  loop++)
      System.out.print(loop);
  3. The flow of control is illustrated:

    Notice that after the statement is executed, control passes to the increment/decrement statement, and then back to the Boolean condition.

  4. Following the general form of section 1 above, the equivalent while loop would look like this:

    statement1;            //  initializes variable
    while (expression2)    //  Boolean expression
    {
      statement;
      statement3;          //  alters key value
    }
    
    
    Coded version:
    
    loop = 1;
    while (loop <= 10)
    {
      System.out.print( loop);
      loop++;
    }
  5. A for loop is appropriate when the initialization value and number of iterations is known in advance. The above example of printing 10 numbers is best solved with a for loop because the number of iterations of the loop is well-defined.

  6. Constructing a for loop is easier than a while loop because the key structural parts of a loop are contained in one line. The initialization, loop boundary, and increment/decrement statement are written in one line. It is also easier to visually check the correctness of a for loop because it is so compact.

  7. A while loop is more appropriate when the boundary condition is tied to some input or changing value inside of the loop.

  8. Here is an interesting application of a for loop to print the alphabet:

    char letter;
    
    for (letter = 'A'; letter <= 'Z'; letter++)
      System.out.print( letter);

    The increment statement letter++ will add one to the ASCII value of letter.

  9. A simple error, but time-consuming to find and fix is the accidental use of a null statement.

    for (loop = 1;  loop <= 10;  loop++);   // note ";"
      System.out.print(loop);

    The semicolon placed at the end of the first line causes the for loop to do "nothing" 10 times. The output statement will only happen once after the for loop has done the null statement 10 times. The null statement can be used as a valid statement in control structures.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.