CS 46A - Lecture 20

Cover page image

Pre-class reading

Partially Filled Arrays

Partially Filled Arrays

Partially Filled Arrays

Self Check 7.9

Write a loop to print the elements of the partially filled array values in reverse order, starting with the last element.

Lecture 20 Clicker Question 1

How do you remove the last element of the (non-empty) partially filled array values?

  1. values.length--;
  2. valuesSize--;
  3. values.remove(values.size() - 1);
  4. values[valuesSize] = 0;

Lecture 20 Clicker Question 2

Why would a programmer use a partially filled array of floating-point numbers instead of an array list?

  1. Because arrays are always more efficient than array lists.
  2. Because you need to use wrapper objects in an ArrayList<Double>, which is less efficient.
  3. Because array lists automatically adjust their capacity.
  4. To avoid roundoff errors.

Common Array Algorithm: Filling

Common Array Algorithm: Computing Sum and Average

Lecture 20 Clicker Question 3

What needs to be done to adapt this algorithm to a completely filled array?

  1. Nothing
  2. Change the enhanced for loop to a regular for loop
  3. Change values.size() to valuesSize
  4. Change values.size() to values.length

Common Array Algorithm: Counting Matches

Common Array Algorithm: Finding the Maximum or Minimum

Lecture 20 Clicker Question 4

Consider the following modification of the algorithm to find a maximum in an array of double values.

double largestYet = 0; 
for (double value : values) 
{ 
   if (value > largestYet) 
      largestYet = value; 
} 
return largestYet;

Which of the following statements is correct?

  1. The algorithm works correctly for all arrays
  2. The algorithm doesn't work for an empty array
  3. The algorithm doesn't work for an array of length 1
  4. The algorithm doesnt' work for an array of negative numbers

Common Array Algorithm: Searching for a Value

Lecture 20 Clicker Question 5

Consider this modification of the linear search algorithm for an array of double values.

public int find(double[] values, double number)
{
   for (int i = 0; i < values.length; i++)
   {
      if (values[i] == number)
         return i;
   }
   return -1;
}

Which of the following statements is true about this algorithm?

  1. In the last line, it should return null
  2. The algorithm doesn't work if all values are negative
  3. The algorithm doesn't return the number that is being searched
  4. The for loop is always traversed values.length times