## CPSC 124, Fall 2005 Answers to Quiz #5

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

Answer: All the elements of an array must be of the same type. That type is called the base type of the array. For example, for the array in problem 2, the base type is Color, since each individual element of the array has type Color.

Question 2: What is the effect of the following code?

```
Color[] primaries;
primaries = new Color[] { Color.RED, Color.GREEN, Color.BLUE };
```

Answer: The first line declares a variable named primaries of type Color[] that is capable of pointing to an array of Colors. The second line creates an actual array and sets primaries to point to it. The array has length 3, and the three elements of the array are set equal to the three Color values Color.RED, Color.GREEN, and Color.BLUE.

Question 3: What value is stored in A[5] after the following code is executed? (No explanation is required, but if your answer is incorrect, an explanation might be worth some partial credit.)

```
int[] A;
A = new int[6];
A[0] = 1;
for (int i = 1; i < 6; i++)
A[i] = 2*A[i-1] + 1;
```

Answer: After the code is executed, A[5] is 63. The array elements are assigned the following values:

```        A[0] = 1
A[1] = 2*A[1-1] + 1 = 2*A[0] + 1 = 2*1 + 1  = 3
A[2] = 2*A[2-1] + 1 = 2*A[1] + 1 = 2*3 + 1  = 7
A[3] = 2*A[3-1] + 1 = 2*A[2] + 1 = 2*7 + 1  = 15
A[4] = 2*A[4-1] + 1 = 2*A[3] + 1 = 2*15 + 1 = 31
A[5] = 2*A[5-1] + 1 = 2*A[4] + 1 = 2*31 + 1 = 63
```

Question 4: Write a subroutine that finds the average of all the numbers in an array. The subroutine has a parameter of type double[]. The return type is double. The return value is the average of all the numbers that are in the parameter array.

Answer: The subroutine can be static or non-static, but static is more natural since it doesn't use any instance variables or instance methods. The name of the subroutine and the name of the array parameter are arbitrary. The idea is to add up the items in the array one-by-one and then divide the sum by the number of items. The number of items is given by the length of the array. Here is one possible answer:

```      public static double average(double[] numList) {

double sum = 0;  // The sum of the items in the array

for (int i = 0; i < numList.length; i++) {
sum = sum + numList[i];  // Add i-th item into the sum.
}

return sum / numList.length;

}
```

David Eck, 18 November 2005