Passing the answer down or returning it up
1 Two places to build the answer
In the last lesson, countDigits built its answer on the way back up. Each frame waited for the call below it, then added 1 to what came back. No frame knew the answer until the base case returned.
There is a second way. When we add up a list by hand, we keep a running total, and at the end the total is the answer. A recursive function can do the same. It hands the total so far to the next call as a parameter.
Both styles solve the same problems. Our running problem shows them side by side: find the largest digit of a number n, where n ≥ 0. For n = 5183, the digits are 5, 1, 8 and 3, so the answer is 8.
2 Returning the answer up
The first style follows the last lesson. The largest digit of 5183 is the larger of two numbers: its last digit, 3, and the largest digit of 518.
- Base case. A number below 10 has one digit, so it is its own largest digit.
- Step. The function takes the last digit, n % 10. It asks the call on n / 10 for the largest digit of the rest, and returns the larger of the two.
The comparison sits after the call, so it runs on the trip up. Here is largestDigit(5183):
| Step | n | lastDigit | What happens |
|---|---|---|---|
| 1 | 5183 | 3 | Calls on 518, waits |
| 2 | 518 | 8 | Calls on 51, waits |
| 3 | 51 | 1 | Calls on 5, waits |
| 4 | 5 | — | Base case: returns 5 |
| 5 | 51 | 1 | Gets 5, returns max(1, 5) = 5 |
| 6 | 518 | 8 | Gets 5, returns max(8, 5) = 8 |
| 7 | 5183 | 3 | Gets 8, returns max(3, 8) = 8 |
Each frame returns its own answer. The call on 51 returns 5, the largest digit of 51. The 8 joins only at step 6, and the full answer exists only when the first call returns.
3 Passing the answer down
The second style keeps a running answer, the way a loop does. We add a parameter, best, that holds the largest digit seen so far. Each call compares its last digit with best and passes the larger one to the call on the rest.
- Base case. When n reaches 0, no digits are left. Every digit has already gone into
best, so the call returnsbest. - Step. The function takes the last digit and works out
newBest, the larger ofbestand that digit. It calls itself on n / 10 withnewBest, and returns whatever that call returns.
The comparison now sits before the call, so it runs on the trip down. Here is the trace, starting with best = 0:
| Step | n | best | lastDigit | newBest |
|---|---|---|---|---|
| 1 | 5183 | 0 | 3 | 3 |
| 2 | 518 | 3 | 8 | 8 |
| 3 | 51 | 8 | 1 | 8 |
| 4 | 5 | 8 | 5 | 8 |
| 5 | 0 | 8 | — | Base case: returns 8 |
The answer is ready at step 5, at the base case. On the trip up, each frame hands the same 8 to the frame below it without changing it.
A problem gives us a fixed function, largestDigit(n), with one parameter. So we keep it, and add a helper, findLargest(n, best), with the extra parameter. largestDigit only makes the first call, with best = 0.
Both versions return 8 for 5183, 9 for 9183, 7 for 7 and 0 for 0.
4 What the parameter needs
Two things decide whether a parameter version is right:
- The start value. The first call's parameter must not change the answer. For a largest digit or a sum, that is 0. For a product, it is 1.
- What it holds at the base case. When the base case runs, every part of the input must already be in the parameter. Then the base case returns the parameter, not a fixed number.
Three mistakes break these rules. Each has an input that shows it:
- Starting a product at 0. The product of the digits of 234 is 24. If the parameter starts at 0, it stays 0 after every multiplication, and the function returns 0.
- Stopping one call early. The first style stops at n < 10. If the parameter version also stops there and returns
best, the leftmost digit never joinsbest. For 9183, it returns 8 instead of 9. - Returning a fixed number at the base case. With
return 0in place ofreturn best, the base case throws the answer away. Every input gives 0.
The second mistake is why the two versions have different base cases. The first style's base case answers for one digit. The parameter version's base case has no digit left to look at.
5 The two styles side by side
Both stacks below are at the base case of largestDigit(5183). In the parameter version, the top frame already holds the answer. In the first version, the top frame knows only 5, and the frames below are still waiting.
| Returning up | Passing down | |
|---|---|---|
| Work runs | After the call | Before the call |
| Base case returns | The answer for the smallest input | The parameter |
| Each frame returns | Its own answer | The same final answer |
| Extra parameter | None | One, with a start value |
Cost. Both make about one call per digit, so the time is the same. The space is the same too. A frame in the parameter version still waits for the call below it, so it stays on the stack until that call returns. Passing the answer down does not make the recursion any shallower.
6 When each style fits
Every problem in this section can be written both ways. One style usually reads more naturally:
- Passing down fits a running result. When a loop would keep a total, a count or a best so far, that variable becomes the parameter.
- Passing down fits collecting a path. When the answer is the list of steps taken to reach the end, the list goes down as a parameter. It is complete at the base case.
- Returning up fits combining answers. When the answer for n is built from the answers for smaller inputs, each call returns its piece. Fibonacci adds the results of two calls. One running value passed down cannot hold both, so returning up is the natural fit.
A list passed down needs care. In most languages, and in C++ with vector<int>&, every frame works on the same list, not a copy. An item that a deep call appends is still there when its frame returns. Copying the list in every call avoids this, but each copy costs time. The backtracking lessons later show how to undo a change instead. The problems in this section pass only numbers.
The sum of the first n numbers, the factorial and the sum of digits each take a few lines either way. Writing each one in both styles is good practice.
The habit to keep: decide where the answer lives before writing the function. If it goes down in a parameter, the base case returns the parameter. If it comes up in return values, the base case returns the answer for the smallest input.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.