The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home Fruitful functions One More Example | |||
One More Example
if (n == 0) { return 1; } else { return n * factorial (n-1); } } From now on I will tend to use the more concise version, but I recommend that you use the more explicit version while you are developing code. When you have it working, you can tighten it up, if you are feeling inspired. After factorial, the classic example of a recursively-defined mathematical function is fibonacci, which has the following definition:
Translated into C++, this is int fibonacci (int n) {if (n == 0 || n == 1) { return 1; } else { return fibonacci (n-1) + fibonacci (n-2); } } If you try to follow the flow of execution here, even for fairly small values of n, your head explodes. But according to the leap of faith, if we assume that the two recursive calls (yes, you can make two recursive calls) work correctly, then it is clear that we get the right result by adding them together.
|
|||
Home Fruitful functions One More Example |