Barbara Ericson, Allen B. Downey, Jason L. Wright (Editor)
Section5.10More recursion
So far we have only learned a small subset of C++, but you might be interested to know that this subset is now a complete programming language, by which I mean that anything that can be computed can be expressed in this language. Any program ever written could be rewritten using only the language features we have used so far (actually, we would need a few commands to control devices like the keyboard, mouse, disks, etc., but that’s all).
Proving that claim is a non-trivial exercise first accomplished by Alan Turing, one of the first computer scientists (well, some would argue that he was a mathematician, but a lot of the early computer scientists started as mathematicians). Accordingly, it is known as the Turing thesis. If you take a course on the Theory of Computation, you will have a chance to see the proof.
To give you an idea of what you can do with the tools we have learned so far, we’ll evaluate a few recursively-defined mathematical functions. A recursive definition is similar to a circular definition, in the sense that the definition contains a reference to the thing being defined. A truly circular definition is typically not very useful:
If you saw that definition in the dictionary, you might be annoyed. On the other hand, if you looked up the definition of the mathematical function factorial, you might get something like:
This definition says that the factorial of 0 is 1, and the factorial of any other value, , is multiplied by the factorial of . So is 3 times , which is 2 times , which is 1 times 0!. Putting it all together, we get equal to 3 times 2 times 1 times 1, which is 6.
If you can write a recursive definition of something, you can usually write a C++ program to evaluate it. The first step is to decide what the parameters are for this function, and what the return type is. With a little thought, you should conclude that factorial takes an integer as a parameter and returns an integer:
This program uses recursion to calculate the factorial of the passed argument. Watch it run step by step and pay attention to the value returned from each call to factorial
Notice that in the last instance of factorial, the local variables recurse and result do not exist because when n=0 the branch that creates them does not execute.