Videos
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!