How compute a cumulative variable through different recursion levels?

1 visualización (últimos 30 días)
Carlos Rueda
Carlos Rueda el 9 de Dic. de 2020
Comentada: Carlos Rueda el 9 de Dic. de 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 comentario
Carlos Rueda
Carlos Rueda el 9 de Dic. de 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.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by