need explanation

May 2, 2013 at 7:08pm
Can someone explain why the two functions act differently? From my point of view they are the same but give different outputs.

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

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

int main()
{
    int index = 0;
    cout << "Enter the desired number: ";
    cin >> index;
    index = (index - 1) + (index - 2); // does not work

    cout << "Fibonacci number is: "  << index << endl;
    return 0;
}
  
May 2, 2013 at 7:53pm
getFibNumber is a recursive function. If you call it with 4, f(4), that function will call f(3) and f(2), which in turn call f(2), f(1), f(1), f(0), and first of those calls f(1) and f(0). That is 9 function calls.

The simple equation:
index = index - 1 + index - 2
Set index=4 =>
index = 4-1 + 4-2
= 3 + 2
= 5
There is nothing recursive in that.
May 2, 2013 at 7:57pm
> why the two functions act differently?
¿two functions? ¿which functions?


`does not work' is not an error message
May 2, 2013 at 8:18pm
The two functions are getFibNumber and the equation in the main. I'm trying to figure out what the difference between the two. Its confusing getFibNumber isn't a loop.
May 2, 2013 at 8:26pm
getFibNumber unrolls:

1
2
3
4
5
getFibNumber(4); calls itself
getFibNumber(4 - 1) + getFibNumber(4 - 2)
...
getFibNumber(1) + getFibNumber(0) + getFibNumber(1) + getFibNumber(1) + getFibNumber(0)
1 + 0 + 1 + 1 + 0 = 3
May 2, 2013 at 8:26pm
keskiverto just explained to you that getFibonacci is a recursive function. It calls itself from within the block, so it is essentially a loop.
getFibonacci calls itself, passing lower values of fibIndex until fibIndex is less than 2.

The real difference between the two methods you show is that getFibonacci can calculate as many iterations as needed while main will not be able to calculate the correct Fibonacci numbers that require more than 3 iterations. In addition, there is no check if index is less than 2, so if the user puts in 1, a negative number is returned.
Last edited on May 2, 2013 at 8:26pm
May 2, 2013 at 8:29pm
@Daleth

A positive integer is returned from getFibNumber(1);
Last edited on May 2, 2013 at 8:29pm
May 2, 2013 at 8:35pm
I was talking about his main function. I guess I could have made that more clear.
1
2
3
4
cin >> index; //user puts in 1
//No check if index < 2 as in getFibonacci
index = (index-1) + (index-2); // index = 0 + -1
cout << "Fibonacci number is: "  << index << endl; // "Fibonacci number is: -1 
May 2, 2013 at 8:45pm
Sorry about that :)
Topic archived. No new replies allowed.