Many mathematical functions are defined recursively, because that is often the simplest way. For example, the factorial of an integer \(n\text{,}\) which is written \(n!\text{,}\) is defined like this:
Donβt confuse the mathematical symbol \(!\text{,}\) which means factorial, with the C++ operator !, which means not. This definition says that factorial(0) is 1, and factorial(n) is n * factorial(n - 1).
To actually see this play out in the code, it can help to break up the steps of the recursive case. This version of factorial does the same math, but prints more information along the way.
It is easier to debug recursion if we store the value that is returned from the recursive call, calculate and store the answer for the current call, and then return the result. That way we can use a debugger or print statements to view how the result is being built up level by level.
The original version of factorial, which did return n * factorial(n - 1);, gave us no chance to see what came back from the call factorial(n - 1) or what value would be returned.
Below is a stack diagram that shows how the value is built up over the recursive calls. This stack diagram cheats a little. Instead of showing the stack at a particular point in time, it shows the final state of each stack frame all at the same time. It also shows what is being returned from one level to the next.
Construct the function sumFrom(int start, int end). It should return the sum of all integers from start to end (inclusive). If start is greater than end, it should return 0.
Build another version of the function sumFrom(int start, int end). It should return the sum of all integers from start to end (inclusive). If start is greater than end, it should return 0.