Question

Ok so I am having trouble understanding exactly how this program works:

#include <iostream>
using namespace std;

int getFibNumber(int fibIndex)
{
    if(fibIndex < 2)
        return fibIndex;
    else
        return getFibNumber(fibIndex - 1) + getFibNumber(fibIndex - 2);
}

int main(int argc, char** argv)
{
    cout << "Enter 0-based index of desired Fibonacci number: ";
    int index = 0;
    cin >> index;

    cout << "Fibonacci number is: " << getFibNumber(index) << endl;

    return 0;
}

Specifically, what does "getFibNumber(...)" do when it reiterates(if that is the correct word)? I can't figure out what it does if the integer "fibIndex" that is passed in is greater than or equal to 2. Sorry to ask such a basic question, but I am really stumped by this and I feel like I'm missing something.

Was it helpful?

Solution

As everyone mentioned here, this is basically recursion.

Just to get a feel of how this program works, I have made the recursion tree with initial fibIndex as 5.

           5                   5 calls 4 and 3.
       /      \                
      4        3               4 calls 3 and 2. 3 calls 2 and 1.
    /   \     /  \
   3     2    2   1            1 is base case, returns 1.
  / \   / \  / \  
 2   1 1  0 1  0               2 is not base case. So calls 1 and 0.
/ \
1  0

OTHER TIPS

This is called recursion. Instead of doing this with a loop it calls the function again, but with a different parameter. Eventually, the base condition will be true, and the function will return, causing the rest of the calls to return also. This can be a very powerful tool in the right situation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top