MATLAB Answers

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

193 views (last 30 days)
123
123 on 17 Mar 2018
Commented: Diego Sánchez Saldaña on 30 Dec 2020 at 15:15
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 Comments

Sign in to comment.

Accepted Answer

vijaya lakshmi
vijaya lakshmi on 20 Mar 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 Comments

Sign in to comment.

More Answers (1)

Community Treasure Hunt

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

Start Hunting!