MATLAB: I want to write a recursive Function that can calculate the sum of all the digit. If the input is 12345 then the answer will be 1+2+3+4+5 , without using string2num and loop.

homeworkrecursive function

function output= digit_sum(n)
if n<10
output=fix(n);
end
if n>0
output=output+digit_sum(n*0.1);
end
end
I wrote this code but the problem I am facing is if i set output=0; anywhere then in all the recalling function process my result will turn to be 0, How to Solve this ?

Best Answer

function output= digit_sum(n,a)
if nargin==1
a=0;
end
if n<10
output=a+fix(n);
else
output=digit_sum(floor(n*.1),a+mod(n,10));
end
end