0

Would like to seek a bit of help from StackOverflow. I am trying to print out the sequence of Fibonacci number and also the number of time the iterative function is called which is supposed to be 5 if the input is 5.

However, I am only getting 4199371 as a count which is a huge number and I am trying to solve the problem since four hours. Hope anyone who could spot some mistake could give a hint.

#include <iostream>
using namespace std;

int fibIterative(int);

int main() 
{
    int num, c1;
    cout <<  "Please enter the number of term of fibonacci number to be displayed: ";
    cin  >> num;

    for (int x = 0; x <= num; x++) 
    {
        cout << fibIterative(x);

        if (fibIterative(x) != 0) {
            c1++;
        }
    }
    cout << endl << "Number of time the iterative function is called: " << c1 << endl;
}

int fibIterative(int n) 
{
   int i = 1;
   int j = 0;
   for(int k = 1; k <= n; k++) {
       j = i + j;
       i = j - i;     
   }
   return j;
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
Headache
  • 27
  • 3

1 Answers1

2

First, initialize the variable

c1 = 0;

so that you will not get any garbage value get printed.


Secondly this:

if (fibIterative(x) != 0)
{
     c1++;
}

will make 2*count - 1 your count. You don't need that.

Edit: I have noticed that you have removed extra c1++; from your first revision. Hence, the above problem is not more valid. However, you are calling the function fibIterative() again to have a check, which is not a good idea. You could have simply print c1-1 at the end, to show the count.


Thirdly,

for (int x = 0; x <= num; x++)

you are starting from 0 till equal to x that means 0,1,2,3,4,5 total of 6 iterations; not 5.

If you meant to start from x = 1, you need this:

for (int x = 1; x <= num; x++)
{            ^
    cout << fibIterative(x) << " ";
    c1++;
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • Thanks for the detailed explanation. I agree with you that it is 6 calls for the iterations function, however the question I am solving requires me to show 5, which upon clarifying with the lecturer, he insist it's 5, sighs. That is why I coded the second error you mentioned but I would clarify with the lecturer again about that part as I personally strongly feel its still 6 iterations. – Headache Jul 29 '18 at 18:58
  • @Headache : see [this](https://en.wikipedia.org/wiki/Fibonacci_number). *the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence*. You had a 0 and 1 starting and was expecting 5 counts. That is why I suspected about it. Now you have referance/ proof. :) – JeJo Jul 29 '18 at 19:02
  • Oh wow, thanks for the link! I will use that to clarify with him. Thanks a lot Jejo! – Headache Jul 29 '18 at 19:06
  • I am new to stackoverflow, I like both answers, its hard to choose, is the green tick very important? – Headache Jul 29 '18 at 19:11