Starting point of our introduction to generic programming: A traditional, overly specific implementation of a sum

Tutorial — starting point

Let's look at a simple, innocent function summing up the values of an array. Let's call this function sum0, because we are going to implement other (more generic) versions of it.

double sum0(double* a, int n) {
  double res = 0;
  for(int i = 0; i < n; ++i)
    res += a[i];
  return res;
}
    

What's wrong with sum0? How can we generalize this function? Take a few minutes to think about it.

Draisine © Frank-Peter Funke - Fotolia.com

Ready? Now let's see, whether we had the same idea ...