Overview

When we first discussed Picture representation, we noted that there were two ways of representing a Picture: as a matrix of pixels and as a single array of pixels. While the former is more intuitive, we examined the latter first as it was simpler to deal with in terms of programming.

Now that we have the basics of working with loops, we’ll be able to work with the matrix version of a picture. This switch will require us to nest loops within each other, a topic you will be introduced to in this reading.

Required Reading

Section 5.1.1 (pp. 131-134) 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. Write a Java expression that gets a specific pixel from a given Picture object using the getPixel method.
  2. Determine the order in which pixels are visited based on the order of nested for loops.

ADVANCED Learning Objectives

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

  1. Read and trace the execution of Java code that contains nested loops over a Picture object.

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. Assume that we have the following Picture variable declaration and initialization:

    Picture myPic = new Picture(FileChooser.pickAFile());

    Write Java expressions that use the getPixel method to get each of the following Pixel objects.

  2. For each of the following sets of nested loops, draw a diagram to illustrate which pixels are modified and the order in which they are modified.

    // Nested loops 1
    for (int x = 0; x < this.getWidth(); x++)
    {
        for (int y = 0; y < this.getHeight(); y++)
        {
            Pixel p = this.getPixel(x,y);
            p.setRed(0);
        }
    }
    
    // Nested loops 2
    for (int y = 0; y < this.getHeight(); y++)
    {
        for (int x = 0; x < this.getWidth(); x++)
        {
            Pixel p = this.getPixel(x,y);
            p.setRed(0);
        }
    }
    
    // Nested loops 3
    for (int x = 0; x < this.getWidth(); x = x + 2)
    {
        for (int y = 0; y < this.getHeight(); y++)
        {
            Pixel p = this.getPixel(x,y);
            p.setRed(0);
        }
    }
    
    // Nested loops 4
    for (int x = 0; x < this.getWidth()/2; x = x + 2)
    {
        for (int y = 0; y < this.getHeight(); y = y + 2)
        {
            Pixel p = this.getPixel(x,y);
            p.setRed(0);
        }
    }