mardi 26 novembre 2019

Recursive function for Fibonacci number

I have to write a simple program as follows: "Given a non-negative integer n, find the nth Fibonacci number using recursion". I think what this means is that, for any value entered by the user, I have to get the Fibonacci number. For example, if the user entered 4, I would have to get the 4th value in the list of Fibonacci numbers (which is 2). Below is what I have written, but there is something wrong with my recursion as it crashes when I run it. Appreciate any help...

int userValue;
int fibo;
int fib(int n);
int fibValue;


int main() {
    cout << "Please provide your value" << endl;
    cin >> userValue;

    while (userValue < 0) {
        cout << "Fibonacci numbers only start at 0, please try again: " << endl;
        cin >> userValue;
    }

    if (userValue == 1 || userValue == 0) {
        cout << "Fibonacci result is: " << userValue << endl;
        return 0;
    }
    else {
        fib(userValue);
        cout << "Fibonacci result is: " << fibValue << endl;
        //return 0;
    }
}

int fib(int n)
{
    fibValue = fib(n - 1) + fib(n - 2);
    return fibValue;
}

Aucun commentaire:

Enregistrer un commentaire