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
46 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
123
el 17 de Mzo. de 2018
Comentada: Diego Sánchez Saldaña
el 30 de Dic. de 2020
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
0 comentarios
Respuesta aceptada
vijaya lakshmi
el 20 de Mzo. de 2018
Hi Matt,
You have written function definition but missed to call the function 'mySum', that is why it is unable to compute anything.
You can refer to the following code snippet to achieve this
numbers=input('get a number');
numbers = num2str(numbers);
out=mySum(numbers)
function result = mySum(numbers)
result=0;
for i=1:length(numbers)
result=str2double(numbers(end))+mySum(numbers(1:end-1));
end
end
Hope this helps you!
0 comentarios
Más respuestas (1)
Saptarshi Neogi
el 30 de Ag. de 2020
Editada: Saptarshi Neogi
el 30 de Ag. de 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 comentario
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!