CS 1401, Quiz 8

Date: Monday, October 30, 2006
Name (please type legibly, ideally in block letters): ______________________________________________________________________

1. Write a piece of code that, given an array h of real numbers, computes the average value of elements in this array.

Solution:

double sum = 0.0;
for (int i = 0; i < h.length; i++)
  {sum = sum + h[i];}
double average = sum/h.length;

2. To check the correctness of the code you wrote in Problem 1, write a piece of code that defines a new array h consisting of 2 elements of type double and assigns, to elements of this array, values 1.0 and 2.0. Trace step-by-step how the piece of code you wrote in Problem 1 will compute the average value of this array.

Solution:

double[] h = {1.0, 2.0};

Tracing:

The fact that we have defined an array h with 2 elements means, in
effect, that we have defined two variables h[0] and h[1]:

 ----
|  \|
 ---\
  h  \
      \|
      - -------
       |  1.0  |  h[0]
        -------
       |  2.0  |  h[1]
        -------

Then, we define a new variable sum and assigning to it a value 0.0:

 -------
|  0.0  |
 -------
   sum

Next, we get to the for-loop. First, we define a new integer variable
i and assign to it the value 0:

 -------   -------
|  0.0  | |   0   |
 -------   -------
   sum        i

We check the condition: the length of our array h is 2, so i is smaller
than this length. Thus, the condition i < h.length is satisfied, and
we implement the operation in the body of the loop. Since i = 0,
we thus perform the operation

  sum = sum + h[0];

In other words, we add the values of sum (0.0) and h[0] (1.0) and place
the result 0.0 + 1.0 = 1.0 into the variable sum:

 -------   -------
|  1.0  | |   0   |
 -------   -------
   sum        i

Then, we go to the update statement i++; this statement adds 1 to i, so
we get:

 -------   -------
|  1.0  | |   1   |
 -------   -------
   sum        i

The condition i < h.length is still satisfied, so we again go inside
the loop. This time, i is 1, so the statement in the body of the loop
becomes

  sum = sum + h[1];

In other words, we add the values of sum (1.0) and h[1] (2.0) and place
the result 1.0 + 2.0 = 3.0 into the variable sum:

 -------   -------
|  3.0  | |   1   |
 -------   -------
   sum        i

Then, we go to the update statement i++; this statement adds 1 to i, so
we get:

 -------   -------
|  3.0  | |   2   |
 -------   -------
   sum        i

The condition i < h.length is no longer satisfied, since i = 2 and the
length of h is also 2. Thus, we get out of the loop.

Finally, we declare a new variable average and assign to it the value
3.0 / 2 = 1.5:

 -------   -------   -------------
|  3.0  | |   2   | |     1.5     |
 -------   -------   -------------
   sum        i         average