Click here to Skip to main content
15,907,497 members
Please Sign up or sign in to vote.
2.33/5 (3 votes)
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
Comments
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    
And what is your doubt?
Richard MacCutchan 25-Nov-13 6:48am    
Hint: Google.

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)
 
Share this answer
 
v2
Comments
Philippe Mori 25-Nov-13 19:34pm    
You don't really need an array. You can store only last and previous value...
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900