CS 1401, Quiz 10, Solutions

Date: Tuesday, April 3, 2007
Name (please type legibly, ideally in block letters): ______________________________________________________________________
Class section (9:00 am or 10:30 am): _______________________________

1. Write a piece of code that, given an array ar of integers, computes the largest element of this array.

 Solution:

int largestSoFar = ar[0];
for (int i = 1; i < ar.length; i++)
  {if (ar[i] > largestSoFar) largestSoFar = ar[i];}

2. To check the correctness of the code you wrote in Problem 1, write a piece of code that defines a new array ar consisting of 2 elements of type integer and assigns, to elements of this array, values 1 and 2. Trace step-by-step how the piece of code you wrote in Problem 1 will compute the largest element of this array.

Solution:

int[] ar = {1, 2};

Tracing:

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

 ----
|  \|
 ---\
  ar \
      \|
      - -------
       |   1   |  ar[0]
        -------
       |   2   |  ar[1]
        -------

Then, we define a new variable largestSoFar and assigning to it a value 1:

 -------
|   1   |
 -------
 largestSoFar

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

 -------       -------
|  1    |     |   1   |
 -------       -------
largestSoFar      i

We check the condition: the length of our array ar is 2, so i is smaller
than this length. Thus, the condition i < ar.length is satisfied, and
we implement the operation in the body of the loop. Since i = 1,
we check the condition ar[1] > largestSoFar, i.e., 2 > 1. This
condition is satisfied, so we replace the previous value of largestSoFar
with a new value 2:

 -------       -------
|  2    |     |   1   |
 -------       -------
largestSoFar      i

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

 -------       -------
|  1    |     |   2   |
 -------       -------
largestSoFar      i

The condition i < ar.length is no longer satisfied, so we stop.