CPSC 124, Spring 2013
Sample Answers to Quiz #8

Question 1. What is meant by the base type of an array?

Answer. An array is a numbered list of "elements." Each element is like a separate variable and can store a value. In Java, all the elements of the array must be of the same type. This type is called the "base type" of the array. For example, the base type of the array in question 2 is double, since all the items in the array are of type double. In general, if T[] is an array type, then T is the base type.

Question 2. What exactly does the following Java code accomplish?

double[] data;
data = new double[25];

Answer. The first line creates a variable, named data, that can refer to an array of double values (but it does not create any actual array). The second line creates an array object and sets data to point to that object. The array has length 25 and has 25 elements of type double, which will be referred to as data[0], data[1], ..., data[24].

Question 3. Suppose that data is the variable from the previous question. Write a Java code segment that will find the sum of all the numbers in the array. (Assume that it has already been filled with values.)

Answer.

double sum;
sum = 0;
for (int i = 0; i < 25; i++) {
   sum = sum + data[i];
}
// The answer is now in sum.

Question 4. Show the output produced by the following Java code segment:

   int[] F;
   F = new int[7];
   F[0] = 1;
   F[1] = 1;
   for (int i = 2; i < 7; i++) {
       F[i] = F[i-1] + F[i-2];
       System.out.println( F[i] );
   }

Answer.

2
3
5
8
13

(The statement "F[i] = F[i-1] + F[i-2]" means that F[i] is computed as the sum if the two previous values in the array. So, for example, F[2] is F[1]+F[0], which is 1+1, or 2. Then F[3] is F[2]+F[1], or 2+1, and so on.)