How compute a cumulative variable through different recursion levels?

조회 수: 3 (최근 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 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