0

I have been trying to do a Fibonacci series using recursive function

A Fibonacci series goes (0,1,1,2,3,5,8,....) so basically a(n) = a(n-2) + a(n-1)

disregarding the first 2 elements (so we start from the second 1) Why does this function not work?

void fibo(int num, int d1, int d2){
int d3 = d1 + d2;
while(num > 0){
    cout << " " << d3 << endl;
    fibo(num-1, d2, d3);
}

Here is the whole line of code

    #include <iostream>

using namespace std;

void fibo(int numb, int d1, int d2);

int main() {
    int d1 = 0;
    int d2 = 1;
    int number = 0;
    cout << "Enter the number of elements in the Fibonacci Series: ";
    cin >> number;
    fibo(number, d1, d2);
    return 0;
}

void fibo(int num, int d1, int d2){
    int d3 = d1 + d2;
    while(num > 0){
        cout << " " << d3 << endl;
        fibo(num-1, d2, d3);
    }
}

Here is the right answer, thanks to Jarod42:

void fibo(int num, int d1, int d2){
    int d3 = d1 + d2;
    num--;
    if(num > 1){
        cout << " " << d3;
        fibo(num, d2, d3);
    }
};
Tahuti
  • 31
  • 2
  • 3
    `while(num > 0)` and you never change `num`... you probably just want `if` instead – Jarod42 Nov 18 '21 at 19:26
  • https://stackoverflow.com/questions/1518726/recursive-fibonacci does this maybe answer your question? – Raqha Nov 18 '21 at 19:30
  • That is what I did. Here is my new function: `void fibo(int num, int d1, int d2){ int d3 = d1 + d2; num--; if(num > 1){ cout << " " << d3; fibo(num, d2, d3); } };` – Tahuti Nov 18 '21 at 19:35

0 Answers0