Overview

In this reading you’ll examine a second type of loop, the while loop. while loops will give us more control over how many times the loop body executes than the “For-Each” loop. With this added control, we’ll be able to do things like modify only a subset of Pixels in a picture. We’ll need to be careful when using while loops though, as they are prone to infinite looping.

Required Reading

Sections 4.3.2-4.3.4 (pp. 93-110) 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. Given a while loop, describe when it will stop executing.
  2. Describe ways in which an infinite loop may be created and how you can stop a program that is stuck in an infinite loop.
  3. Compare and contrast the three types of comments in Java.
  4. Describe what the ++ and -- operators do.
  5. Use the picture explorer to compare before/after versions of a picture.

ADVANCED Learning Objectives

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

  1. Trace the execution of a while loop that modifies a Picture, drawing a memory model as you trace.
  2. Given some Java code, determine whether it will have an infinite 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 the loop body of the following loop execute?

    int i = 0;
    while (i < 10)
    {
        System.out.println("Howdy, partner!");
        i++;
    }
  2. If we replace the i++ in the code above with “i = i + 2”, how many times would the loop body execute?

  3. Part A: What is printed after executing the following code?

    int n = 0;
    // n = n + 2;
    System.out.println(n);
    n++;
    /*
    System.out.println(n);
    */

    Part B: Explain why the code in Part A printed what it did.

  4. Download this cupcake picture to your computer. Use the Picture Explorer in DrJava to determine the RGB values at coordinate (300, 360).