Create a program that asks a user to input a number and then finds the sum of digits of the number using recursion. for example 341 = 3+4+1 = 8
Ältere Kommentare anzeigen
This is what i have but it wont compute anything..
number = input('Enter a number here:');
function result = mySum(numbers)
numbers = num2str(number) - '0';
if length(numbers) == 0
result = 0;
else
result = numbers(end) + mySum(numbers(1:end - 1));
end
end
Akzeptierte Antwort
Weitere Antworten (1)
Saptarshi Neogi
am 30 Aug. 2020
Bearbeitet: Saptarshi Neogi
am 30 Aug. 2020
% This program does not require any inbuilt functions.
function x = digit_sum(n)
x=0;
if n>0
x=mod(n,10)+digit_sum(floor(n./10));%recursive
end
1 Kommentar
Diego Sánchez Saldaña
am 30 Dez. 2020
Very nice and useful answer! thank you so much!
Kategorien
Mehr zu Startup and Shutdown finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!