Overview

Having now seen two types of loop (“For-each” and “while”), we’ll now turn our attention to the final type of Java loop: the “for” loop. Despite the name, for loops are more similar in structure to while loops than they are to “For-each” loops.

for loops have the trickiest syntax of all the types of loops. Furthermore, they don’t provide any functionality beyond while loops. You may be wondering: “Why bother?” The answer lies in fact that compact representation of for loops reduces the chance of bugs such as infinite loops. With some experience, the syntax of for loops will become less mysterious and reduced possibility of bugs will become more obvious.

Required Reading

Sections 4.3.5-4.4 (pp. 110-126) from the course textbook.

Learning Objectives

BASIC Learning Objectives

Each student will be responsible for learning and demonstrating proficiency in the following objectives PRIOR to the class meeting. The reading quiz will test these objectives.

  1. Describe the benefit(s) of using hierarchical decomposition.
  2. Given the location of a variable declaration, determine its scope.
  3. Describe the roles of the initialization area, continuation test, and change area in a for loop.
  4. Compare and contrast the flowcharts of while and for loops.
  5. Describe how each pixel is manipulated to:

ADVANCED Learning Objectives

The following objectives should be mastered by each student DURING and FOLLOWING the class session through active work and practice.

  1. Describe how invoking a method assigns values to the method’s parameters.
  2. Read and trace execution of a code with a for loop (using a single array of pixels).
  3. Find and fix array index out-of-bounds exceptions in a for loop.

Pre-class Exercises

These exercises are geared towards mastering the BASIC learning objectives listed above. You are expected to submit them before class and it is highly recommended that you complete them before attempting the reading quiz.

  1. How many times will “Hello” be printed after executing the following code?

    for (int t = 10; t < 20; t++)
    {
        System.out.println("Hello");
    }
  2. How many times will “Goodbye” be printed after executing the following code?

    for (int q = 0; q <= 8; q = q + 2)
    {
        System.out.println("Goodbye");
    }
  3. Consider the following Java code:

    int x = 0;
    while (x < pixelArray.length)
    {
        pixelArray[x].setBlue(0);
        x = x + 1;
    }

    If we wanted to write this code using a for loop instead of a while loop, what code will we have for the following parts of the for loop: