How compute a cumulative variable through different recursion levels?

1 vue (au cours des 30 derniers jours)
Carlos Rueda
Carlos Rueda le 9 Déc 2020
Commenté : Carlos Rueda le 9 Déc 2020
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 commentaire
Carlos Rueda
Carlos Rueda le 9 Déc 2020
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.

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by