I want to write a recursive Function that can calculate the sum of all the digit. If the input is 12345 then the answer will be 1+2+3+4+5 , without using string2num and loop.
I wrote this code but the problem I am facing is if i set output=0; anywhere then in all the recalling function process my result will turn to be 0, How to Solve this ?
Maybe you should take a step back and write down the algorithm on paper using words instead of code. Then take a simple 2 digit example and run it through your algorithm on paper. Once you have things figured out for your algorithm, then turn it into code and start testing. That will force you to understand the algorithm first, before you even get to the coding stage.
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
4 Comments
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/580833-i-want-to-write-a-recursive-function-that-can-calculate-the-sum-of-all-the-digit-if-the-input-is-12#comment_976302
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/580833-i-want-to-write-a-recursive-function-that-can-calculate-the-sum-of-all-the-digit-if-the-input-is-12#comment_976302
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/580833-i-want-to-write-a-recursive-function-that-can-calculate-the-sum-of-all-the-digit-if-the-input-is-12#comment_976326
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/580833-i-want-to-write-a-recursive-function-that-can-calculate-the-sum-of-all-the-digit-if-the-input-is-12#comment_976326
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/580833-i-want-to-write-a-recursive-function-that-can-calculate-the-sum-of-all-the-digit-if-the-input-is-12#comment_976356
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/580833-i-want-to-write-a-recursive-function-that-can-calculate-the-sum-of-all-the-digit-if-the-input-is-12#comment_976356
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/580833-i-want-to-write-a-recursive-function-that-can-calculate-the-sum-of-all-the-digit-if-the-input-is-12#comment_976416
Direct link to this comment
https://www.mathworks.com/matlabcentral/answers/580833-i-want-to-write-a-recursive-function-that-can-calculate-the-sum-of-all-the-digit-if-the-input-is-12#comment_976416
Sign in to comment.