Data Structures, Algorithms, & Applications in Java
Chapter 1, Exercise 21

The code for the method utilities.MyMath.sum is given below.


/** Generic sum method.
  * @return null if array has no objects and
  * sum of the objects a[0:n-1] otherwise */
public static Computable sum(Computable [] a, int n)
{
   if (a.length == 0) return null;
   Computable sum = (Computable) a[0].zero();
   for (int i = 0; i < n; i++)
      sum.increment(a[i]);
   return sum;
}