## CPSC 124, Fall 2001 Quiz #7, December 3

This is the third quiz in CPSC 124: Introductory Programming.

Question 1: What does the computer do when it executes the following statement? Try to give as complete an answer as possible.

```         Color[] pallette = new Color[12];
```

Answer: This is a declaration statement, that declares and initializes a variable named pallette of type Color[]. The initial value of this variable is a newly created array that has space for 12 items. To be specific about what the computer does: It creates a new 12-element array object on the heap, and it fills each space in that array with null. It allocates a memory space for the variable, pallette. And it stores a pointer to the new array object in that memory space.

Question 2: Vector is a standard class in Java. What is a Vector? What is the main service that Vectors provide to programmers?

Answer: A Vector contains a numbered sequence of values of type Object. In this way, it is similar to an array of type Object[]. However, unlike an array a Vector does not have a fixed length. The main service that Vectors provide to programmers is that they will grow automatically when new elements are added to them (using the addElement() method).

Question 3: Consider the following declarations

```         class Date {  //Represents a date as a month, day, and year
int month, day, year;
}
Date[] dateList = new Date[1000];
```

Suppose that the array dateList has already been filled with 1000 dates. Write some Java code that will count the number of dates in the array that are in the year 2001.

Answer: (Note the name of the array is dateList, the length of the array is dataList.length, and the i-th element in the array is dateList[i]. We have to check the year in each element of the array. The name for the year in dateList[i] is dateList[i].year. To answer the question, look at each element in the array. Whenever the year in that element is equal to 2001, add 1 to a counter.)

```            int count = 0;
for (int i = 0; i < dateList.length; i++) {
if ( dateList[i].year == 2001 )
count = count + 1;
}
// At this point, count holds the number of dates in the
// array that are in the year 2001.
```

Question 4: Write a complete subroutine that finds the average of all the numbers in an array of double. The subroutine should have one parameter, of type double[], and a return value of type double.

Answer: (This should probably be a static subroutine, since it doesn't depend on any object. The average can be computed by adding up all the elements in the given array and dividing the sum by the number of elements in the array. Note that if the array is named A, then the number of elements in the array is A.length.)

```            static double average( double[] A ) {
double sum;  // Sum of elements of A.
for (int i = 0; i < A.length; i++) {
sum = sum + A[i];  // Add i-th element of A to the sum.
}
return  ( sum / A.length );
}
```

David Eck, eck@hws.edu