## CS 124, Fall 2009 Solutions to Quiz #6

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

Answer: An array in Java is a list of items, where all the items in the list are of the same type. That type is called the base type of the array. For example, the base type of an array of type int[] is int, and the base type of an array of type String[] is String.

2. Explain the meaning of the notation A[i] in Java.

Answer: For this notation to be valid in a program, A must be an array. (That is, A must have been declared as a variable of array type, and it must point to an array object.) Furthermore, i has to be an integer variable (of type int, long, or some other integer type). In that case, A[i] is simply a name for the i-th element of the array A. That is it refers to position number i in the array. A[i] is in effect a variable, and it can be used like any other variable. You can use it in expressions, pass it as a parameter, and assign values to it.

3. Suppose that numList is an array of type double[]. (That is, numList is an array of doubles.) Write a code segment that will compute and print the sum of all the numbers in numList.

Answer: This is completely standard array processing example:

```         double sum = 0;
for (int i = 0; i < numList.length; i++) {
sum += numList[i];
}
System.out.println("The sum is " + sum);
```

4. Consider the following code segment. Show the contents of the array A after this code segment has been executed.

```   int[] A;
A = new int;
A = 0;
for (int i = 1; i < A.length; i++) {
A[i] = (2 * A[i-1]) + 1;
}
```

Answer: The first time that the four loop is executed, i is 1 and i-1 is 0, so the assignment statement means A = (2*A) + 1. Since A is 0, the value that is assigned to A is 1. The next time through the for loop, i is 2 and i-1 is 1, so the assignment statement means A = (2*A) + 1. Since A now has the value 1, the value that is assigned to A is 2*1+1, or 3. This continues for the remaining elements of the array. The value of each element is twice the value of the previous element, plus 1. This assigns 2*3+1, or 7, to A and 2*7+1, or 15, to A. To show the contents of the array as a picture, we could draw:

```
+--------+
A: ----->  |   (5)  |  (length)
+--------+
0 |     0  |
+--------+
1 |     1  |
+--------+
2 |     3  |
+--------+
3 |     7  |
+--------+
4 |    15  |
+--------+
```