So, I'm just starting to learn recursion and get a little fixated on concepts. Here is the solution I found for the digit function (f (126) = 1 + 2 + 6 = 9):
function sumDigits(num, sum){
if (num === 0) {
return sum;
} else {
sum += num % 10;
num = Math.floor(num / 10);
return sumDigits(num, sum);
}}
I followed it to the bottom, so far everything makes sense:
**Trace**
f(126, 0)
{
sum = 6
num = 12
f(12, 6)
}
f(12, 6)
{
sum = 8
num = 1
f(1, 8)
}
f(1, 8)
{
sum = 9
num = 0
f(0, 9)
}
f(0, 9) = 9
I think it makes no sense to me HOW does the base case go back during unwinding? How exactly does he travel?
I expect facepalm, but until I understand, I don't think I can replicate this solution.
Thank you for your help!
source
share