14A. Scan Algorithms on Arrays


Summing an array

An array is a ready-made sequence for a scan algorithm. But you scan an array by looking at the sequence of array indices.

Here is an example, a function that adds up the first n values in an array. The indices are 0, 1, …, n − 1.

  // sum(A,n) returns A[0] + A[1] + ... + A[n-1].

  int sum(const int A[], const int n)
  {
    int total = 0;
    for(int i = 0; i < n; i++)
    {
      total += A[i];
    }
    return total;
  }

Finding the smallest value in an array

A scan algorithm that finds the smallest value in a sequence keeps track of the smallest value in the prefix that the algorithm has looked at so far.

It only makes sense to find the smallest value in an array that has at least one value in it. The following algorithm uses A[0] as an initial value and loops over the sequence of indices 1, 2, …, n − 1.

  // smallest(A, n) returns the smallest value in
  // A[0, ..., n-1].  
  //
  // Requirement: n > 0.

  int smallest(const int A[], const int n)
  {
    int small = A[0];
    for(int i = 1; i < n; i++)
    {
      small = min(small, A[i]);
    }
    return small;
  }

Exercises

  1. Write a C++ definition of function numOdds(A, n), which returns the number of odd values in array A[0, ..., n−1]. Assume that A is an array of ints. Answer

  2. Assume that function isPrime(n), which returns true just when n is prime, is available. Write a C++ definition of function numPrime(A, n), which returns a count of how many of the values in A[0, …, n − 1] are prime. Assume that all integers have type int. Answer