15,907,497 members
See more:
Hi friends.

I want to write a recursive function to print N first element into the recursive function.
But i dont know how do it?
for example recalling Fib(8), then it should print 0 1 1 2 3 5 8 13

thanks.
Posted
Updated 25-Nov-13 0:24am
v2
Stefan_Lang 25-Nov-13 6:16am
That is not a question What have you tried? What is your problem? What is not working?

Also: be advised that we won't do other peoples' homework - you're supposed to do it yourself. We may help if you're stuck with a *specific* problem. but for that we need a *specific* question.
CPallini 25-Nov-13 6:24am
Richard MacCutchan 25-Nov-13 6:48am

## Solution 1

If you try to solve with recursive approch
with a fucnction like this :

C++
```int F(int n)
{
if(n==0 || n==1){
cout<<1<<" ";
return 1;
}
int RET=F(n-2)+F(n-1);
cout<<RET<<" ";
}```

this Function would be O(2^N)

i suggest you Dyanmic approch
First try to fill a Table of F[]

C++
```int F[maxn];
F[0]=F[1]=1;

for(int i=2;i<maxn;i++)>
F[i]=F[i-1]+F[i-2];```

now you have Fibonacci Sequenced Saved in An Array with The Time Order O(N)

v2
Philippe Mori 25-Nov-13 19:34pm
You don't really need an array. You can store only last and previous value...

## Solution 2

How to define a recursive function in C/C++:
C++
```int foo(int n) {
int result = 0;
// step 0: pin down the result value(s) for starting the recursion
const int first_value = 1;
// step 1: test if you're at the root of the recursion
if (0 == n)
result = first_value;
else {
// step 2: determine previous result through recursion
int previous_result = foo(n-1);
// step 3: determine result from previous result
result = n*previous_result;
}
return result;
}```

Notes:
- step 0 may require more than one value if your recursion requires more than 1 value to calculate the next one.
- step 1 may require multiple checks if you have multiple starting values
- bonus hint: you should add an additional check ( e. g. `if (n < 0)` ) to make sure you have a valid argument and won't accidentally run into an endless loop.

Read and understand the notes to adapt this example code for the fibonacci sequence. I won't do that for you since it smells of homework, and I can't help you learn if I do it for you.