01: Variables and Scope

Submit this homework using Gradescope. Do not email us your homework or bring a paper copy to class: we will not accept it.

Logging into Gradescope

You should already have an account on Gradescope (https://gradescope.com/) if you added this course before the first day of classes. If not, go to the Gradescope web site and sign up using the email address that you have listed in SPIRE. When you sign up in Gradescope, you’ll need a course entry code. Ours is on the course Moodle page.

Do not wait until the due date to start this process. If the Gradescope site tells you it does not recognize your email address, you should contact the course staff immediately to create an account for you. “I added the course late and didn’t know I needed to ask for a Gradescope account”, “I forgot my Gradescope password” and the like will not be accepted as an excuse for not submitting this or any other assignment on time.

The homework

code for question 1:

/* Assume these are instance variables */
int w = 3;
int x;
int y;
int z;
/* and assume these lines happen inside the body of a method */
x = x + 5;
y = 12;
z = y;
y = y / 2;

code for question 2:

int[] array1 = new int[2];
int[] array2 = new int[2];
int[] array3 = array1;
for (int i = 0; i < 2; i++) {
  array1[i] = i;
  array2[i] = i * 2;
}
array3[0] = 5;
  1. (2 points) What are the values of w, x, y, and z at the end of this code above?

  2. (5 points) Consider the second code snippet above. In the box-and-arrow style we used in class, draw the variables (array1, array2, and array3) and the arrays themselves. Label each variable with its name and type as appropriate; label the arrays with their type, and show the value stored in each cell of the arrays.

  3. (1 point each) Consider a linear function f(x) = mx + b.

    a. Write a method to compute the value of such a function, given m, x, and b. The method should have the signature double compute(double m, double x, double b). Feel free to write this method in an IDE.

    b. How much space (in terms of the size of double values) does the JVM lay out on the stack when this method is invoked? In other words, space for how many doubles must be set aside when this method is invoked? Only consider method arguments and return values for this method, and not any others your code may call.