What you have there is an iterative solution, not a recursive one.
Recursion involves defining the problems in terms of a simpler version of the problem, all the time working towards a fixed end point.
The fixed end point in this case is any number less than 10, for which the value is that digit.
The transition to a simpler case (for numbers greater than 9) is simply to add the least significant digit to the result of the number divided by ten (integer division).
Since it's classwork, pseudo-code only I'm afraid.
def digitSum (n):
if n < 10:
return n
return (n % 10) + digitSum (n / 10)
If you follow that for the number 314
, you'll see what happens.
- At recursion level one,
n == 314
so it calculates 314 % 10
to get 4
and calls digitSum(31)
.
- At recursion level two,
n == 31
so it calculates 31 % 10
to get 1
and calls digitSum(3)
.
- At recursion level three,
n == 3
so it just returns 3
- Back up to level two, that's added to the remembered
1
and returned as 4
.
- Back up to level one, that's added to the remembered
4
and returned as 8
.
Hence you end up with the digit sum of 8
for the number 314
.