Review for Quiz 1

Question 1-1

In your own words, describe what distinguishes a class variable from an instance variable. (I'm not asking about how you distinguish them syntactically in Java - I'm asking how their behavior is different.)

Question 1-2

Consider the following method to compute the greatest common denominator of two numbers.

public static int sqrt(int n) {
    int x = 0;
    int d = n;
    while(d > 0) {
        if((x + d) * (x + d) <= n) x += d;
        d /= 2;
    }
    return x;
}
Say we call sqrt(32). Show how the values of x and d change as the computer continues through the method.
x
d

Question 1-3

Draw a picture of the window drawn by the following method.

import csbsju.cs160.*;

public class GraphicsExample {
    public static void run() {
        DrawableFrame window = new DrawableFrame();
        window.show();

        Graphics g = window.getGraphics();
        g.fillOval(50, 50, 100, 100);
        g.setColor(Color.white);
        g.fillRect(0, 0, 100, 200);
        g.fillOval(75, 50, 50, 50);
        g.setColor(Color.black);
        g.fillOval(75, 100, 50, 50);
        g.drawOval(50, 50, 100, 100);
    }
}

Question 1-4

Write a method that reads in a sequence of integers from the user, terminated by a 0, and displays the sum of the numbers typed. Here's an example transcript (user input in boldface).

4
2
-3
0
3
import csbsju.cs160.*;

public class FindSum {
    public static void run() {
        // your code here...



    }
}

Solutions

Solution 1-1

A class variable is at a fixed location in memory. There can only be one copy of it available at any time. An instance variable, on the other hand, is associated with each individual instance of the class.

Solution 1-2

x  0  4  5
d 32 16  8  4  2  1  0

Solution 1-3

Solution 1-4

import csbsju.cs160.*;

public class FindSum {
    public static void run() {
        int total = 0;
        while(true) {
            int input = IO.readInt();
            if(input == 0) break;
            total += input;
        }
        IO.println(total);
    }
}