0

So far I have been able to use recursion to print out the fibonacci sequence. For example, the first 6 terms (including the 0'th term) in the sequence is:

6

13 8 5 3 2 1 1

but Im not sure how i'm supposed to use this to print out the entirety of a fibonacci tree. When the program input is 6, it's supposed to print:

6
13 8 5 3 2 1 1 1 2 1 1 3 2 1 1 1 5 3 2 1 1 1 2 1 1

and my code so far is:

#include <iostream>
#include <math.h>
#include <vector>
#include <string>

using namespace std;

std::vector<int> list;

int fib(int num);

int main() {
    int input, depth = 0, leafs = 0, size = 0;

    cin >> input;
    int temp = input;

    while (temp >= 0) {
        cout << fib(temp) << " ";
        temp--;
    }


    return 0;
}

int fib(int n) {
    if (n <= 1) {
        return 1;
    } else {
        return fib(n-1) + fib(n-2);
    }
}
Dov Royal
  • 49
  • 2
  • 9

1 Answers1

1

If you want to print everything, you need also to all the function to print everything:

int fib(int n) {
    if (n <= 1) {
        std::cout << 1 << " ";
        return 1;
    } else {
        int f1 = fib(n-1);
        int f2 = fib(n-2);
        std::cout << f1 + f2 << " ";
        return f1 + f2;
    }
}
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62