# 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.

109 views (last 30 days)
Asif Ahmed on 17 Aug 2020
Answered: Farhath Surayya on 19 Nov 2020
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 ? Show 1 older comment
Asif Ahmed on 17 Aug 2020
function output= digit_sum(n)
output=0;
if n<10
output=fix(n);
end
if n>0
output=digit_sum(n*0.1);
end
end
If I set output=0 anywhere then the result is coming 0 .
James Tursa on 17 Aug 2020
Maybe you should take a step back and write down the algorithm on paper using words instead of code. Then take a simple 2 digit example and run it through your algorithm on paper. Once you have things figured out for your algorithm, then turn it into code and start testing. That will force you to understand the algorithm first, before you even get to the coding stage.
Asif Ahmed on 17 Aug 2020

David Hill on 17 Aug 2020
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

Asif Ahmed on 17 Aug 2020
There is just one input number digit_sum(n) .I just tried this but the output says 'Unrecognized FUnction or variable 'output'' Where i am mistaking ?
function output= digit_sum(n)
if n>0
output= (n/10 -fix(n/10))*10+digit_sum(fix(n*0.1));
end
end
David Hill on 17 Aug 2020
Using nargin, your function can have 1 or more inputs.
output = digit_sum(12345);
Try the above on my function.
Asif Ahmed on 17 Aug 2020
function output= digit_sum(n)
if n<10
output=fix(n);
end
if n>0
output=((n/10 -fix(n/10))*10)+digit_sum(fix(n*0.1));
end
end
Thanks , I got the problem where i was mistaking,Now the code runs fine. Thanks for your help.
function output= digit_sum(n)
if n<10
output=fix(n);
end
if n>0
output=mod(n,10)+digit_sum(fix(n*0.1));
end
end

Saptarshi Neogi on 30 Aug 2020
You can do this with any inbuit functions.
function x = digit_sum(n)
x=0;
if n>0
x=mod(n,10)+digit_sum(floor(n./10));%recursive
end

Sanjay Raju on 13 Sep 2020
function x=digit_sum(inp)
if inp<10
x=inp;
else
x = mod(inp,10) + digit_sum(fix(inp/10));
end
end

Farhath Surayya on 19 Nov 2020
function output= digit_sum(n) if n<10 output=fix(n); end if n>0 output=output+digit_sum(n*0.1); end end