Suppose we want to write a recursive definition of sum(n) = 1 + 2 + … + n. Here are two facts.
sum(1) = 1.
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.
Let's define largest(A, n), the largest of the first n values in array A. Here are the facts.
largest(A, 1) = A[0].
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]); } }
Write facts about function sumsq(n), which returns 12 + 22 + … n2, then convert the facts to a recursive definition of sumsq(n). Answer
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