フィルターのクリア

How compute a cumulative variable through different recursion levels?

1 回表示 (過去 30 日間)
Carlos Rueda
Carlos Rueda 2020 年 12 月 9 日
コメント済み: Carlos Rueda 2020 年 12 月 9 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by