Fibonacci series using a recursive function

• 01-23-2002
Dargoth
Fibonacci series using a recursive function
Hello all :) this my first post, so bear with me if I don't do something correctly.:eek:

This is my question: below I have the format for my recursive function but am really unsure of what I need to put in the Underscore areas ?

If anyone has any ideas, I have never done a Fibonacci series of numbers before, so I'm lost as to how it has to be set up.

#include <iostream>
using namespace std;

unsigned long fib(int nth);

void main()
{
int nth=0;

cout << "Enter an integer from 1 to 30: ";

while (!(cin >> nth))
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << " Please! Enter a number: ";
}
if((nth < 1) || (nth > 30))
cout << "\nSorry. "
<< "Number isn't in the right range.";
else
{
unsigned long fibValue;
fib(int fibValue);

cout << "\nThe value of number " << nth;
cout << " in the series is " << fibValue
<< ".\n";
}
}

// Recursive function
unsigned long fib(int nth)
{
if(______)
return(___);
else
return(_________ + ____________);
}
• 01-23-2002
mix0matt
Well since you can find an implementation of the recursive fibonacci function in any decent intro to C++ book, i'll do it for you, and since i'm feeling nice here's the rest of the program. if you have any questions about what i did and care about learning it, feel free to ask....

Code:

```#include <iostream> using std::cin; using std::cout; using std::endl; unsigned long fibValue (unsigned long); int main () {     unsigned long nth = 0;     cout << "Enter an integer from 1 to 30:  \n";     do {         cin >> nth;         if ((nth < 1) || (nth > 30))             cout << "Sorry. . . Number isn't in the right range."                     << "  Try again.\n";     } while ((nth < 1) || (nth > 30));     cout << "The integer is the " << fibValue(nth) <<" number in the series."             << endl;     return 0; } unsigned long fibValue (unsigned long n) {     if (n == 0 || n == 1)         return n;     else         return fibValue (n-1) + fibValue (n-2); }```
• 01-23-2002
*ClowPimp*
Straight recursive fib is horribly inefficient, this method will probably impress your teachers

Code:

```unsigned long fibValue (unsigned long n) {     static fibVals[MAX_FIB_VAL] = {0}     if (n == 0 || n == 1)         return fibVals[n] = n;     else if (fibVals[n] == 0)         return fibVals[n] = fibValue(n-1) + fibVal(n-2);     // else     return fibVal[n]; }```
Since this code doesnt branch uncontrollably, it will work for much larger numbers
• 02-04-2002
Dargoth
I thank you all for the replies :)