14C. Using Equations

Suppose we want to write a recursive definition of sum(n) = 1 + 2 + … + n. Here are two facts.

  1. sum(1) = 1.

  2. When n > 1,

    sum(n) = 1 + 2 + … + (n − 1) + n
      = sum(n − 1) + n

    For example, sum(3) = 1 + 2 + 3 = 6, and sum(4) = 1 + 2 + 3 + 4 = 10. Clearly, sum(4) = sum(3) + 4.

Here is a definition of sum(n) based directly on those facts.

  int sum(const int n)
  {
    if(n == 1)
    {
      return 1;
    }
    else
    {
      return sum(n-1) + n.
    }
  }

The point is that we can plan the algorithm by thinking about facts, and then convert the facts to a C++ function definition. That approach tends to lead to function definitions that work right away, without any need for debugging.


largest(A, n)

Let's define largest(A, n), the largest of the first n values in array A. Here are the facts.

  1. largest(A, 1) = A[0].

  2. When n > 1, largest(A, n) = max(largest(A, n−1), A[n−1])

Check those facts using examples. Converting the facts to a recursive function definition is straightforward.

  int largest(const int A[], const int n)
  {
    if(n == 1)
    {
      return A[0];
    }
    else
    {
      return max(largest(A,n-1), A[n-1]);
    }
  }

Exercises

  1. Write facts about function sumsq(n), which returns 12 + 22 + … n2, then convert the facts to a recursive definition of sumsq(n). Answer

  2. Write facts about function product(A, n), which returns A[0] * A[1] * … * A[n−]. Define product(A, 0) = 1. Then convert the facts to a recursive definition of product. Answer