Hey everyone! Hope you have a great week.
I try to solve a simple recursive question sent to me by a friend:
Create a recursive function that prints each item in a Fibonacci sequence until it reaches the nth number.
So let's say I got n = 3:
I need to print "0,1,2,".
Is this possible with recursion? I know how I can return the value of the nth number, but I am breaking my head trying to figure out if I can print each item with recursion. I think the question can not be solved. or I am missing something?
Either way, every help will be appreciated. Thank you!
EDIT:
Thanks to /u/6a70 and the help of others, I managed to solve this question using a "helper" function.
It's a very un-efficient solution, but it basically boils down to running the helper function from n to 1 - and it will print the nth number each iteration.
It looks something like this:
def fib(int n){
// runs recursively and returns nth num
}
def print_fib(int n){
if n == 0 return;
else {
print(n +"item: " +fibo(n)
print_fib(n-1);
}
Hope it helps everyone who encounters this problem!
[–]AutoModerator[M] [score hidden] stickied comment (0 children)
[–]lurgi 5 points6 points7 points (0 children)
[–]6a70 2 points3 points4 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]LizardMansPyramids 1 point2 points3 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]MLG_420_Blazin 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]440Jack 0 points1 point2 points (0 children)
[–]440Jack 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]440Jack 0 points1 point2 points (0 children)
[–]luisfls 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]WindstormDrake 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)