How compute a cumulative variable through different recursion levels?

3 次查看(过去 30 天)
Hello all,
I am actually just getting started with recursion and I am struggling with it. I have to solve a problem whose concept is actually very easy, but I don't get right to use the recursion. Without usign loops and any character conversion function, I have to compute the sum of the digits of a number by a recursive function. If the input is 15, the result is 6, if the input is 123, the result is also 6.
This is my code so far:
function result=digit_sum(input)
a=input/10;
b=floor(rem(input,10));
if a<10
result=floor(a)+b;
else
%sum here the current value of b for recursion
result=digit_sum(a);
end
end
The concept is very easy and funny thing is that the code actually works with 2-digt inputs. With 3 or more digit inputs the could will go through all necessary recursion levels but I don't know how to work with b so that it gets summed with each recursion level.
I assume I need a line of code to sum b afer the else statement, but honestly, I do not know how. If anyone could give a hint I appreciate.
BR,
Carlos.
  1 个评论
Carlos Rueda
Carlos Rueda 2020-12-9
Well, after rethinking this a bit I got the solution, just lurking before my eyes :). I will be happy to tell anyone who is interested and just like me getting started.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by