0

How can I do this recursively?

For homework i need to fill an array using the digits of a natural number. For example if i had the number 32617 my array needs to be a[0]=3, a[1]=2, a[2]=6, a[3]=1, a[4]=7. I have no idea how to do this recursively. The only thing i thought of is how to isolate the numbers. If i had that same number i would divide it by 10 to the power of n-1. n being the number of digits the natural number has. Then i would take the original number and subtract the isolated number and multiply it by 10 to the power of n-1 to get the original number but without the first digit and then repeat until i have one number. The things is i don't know if my logic is correct, or if there is a way to apply it recursively. If someone can help in anyway it would be much appreciated.

29th Feb 2020, 2:21 PM
Grumboll
2 Answers
+ 3
the function homework has two params: the array and the number. if number < 10 insert number at beginning of array and return array else insert number mod 10 at beginning of array and return homework with number//10 and array,. eg number is 4567 homework(4567,[])calls homework(456,[7]) calls homework(45,[6,7] calls homework(4,[5,6,7])returns [4,5,6,7]
29th Feb 2020, 2:48 PM
Oma Falk
Oma Falk - avatar
+ 5
I am unclear with one thing : Is Recursive a requirement of your homework? Let's break this assignment into three parts : 1. Extracting digit with while loop. Do you know how to do it with while loop? From your logic, seems you don't know. Actually the digits are usually extracted inversely 2. Converting to recursive function. If you know how to extract digit with while loop, you can convert it to recursive. 3. Putting digits to an array. Usually the digits are extracted inversely, so this may help : https://stackoverflow.com/questions/33983531/c-append-to-front-add-to-back-array-of-ints
29th Feb 2020, 2:23 PM
Gordon
Gordon - avatar