First off, it's not homework. I'm practicing examples from http://codingbat.com/java/Recursion-1. Every time I think I'm beginning to understand recursion, I run into a problem that makes me realize I have no idea, and the only thing tutors or internet explanations ever say is that "the function calls itself until the base case is met."
public int sumDigits(int n) {
if(n < 10) {
return n;
} else return sumDigits(n/10) + n % 10;
}
If I pass 115 to this on my computer, the output is 7 (as it should), but I don't understand how the program comes to this conclusion. Here is how I see it:
115 is not less than 10, so return the program with 115/10 (which is 11). 11 is not less than 10, so return the program with 11/10 (which is 1). Add this to 115%10 (which is 5). So how does this program get 7???
It seems like no matter how many examples I look at, I cannot find a pattern in how this works.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…