Search code examples
c++fibonaccivariable-length-array

C++ Fibonacci number generator not working. Why?


I just wanna know why does this method to get the fibonacci number not work thanks.

#include <iostream>
#include <cctype>
#include <cmath>
using namespace std;

int fibonacci()
{
    cout << "enter sequence num: " << endl;
    int num;
    cin >> num;
    int list[num] = {0, 1};
    int x;

    if (num == 1)
    {
        cout << "the " << num << " fibo num is " << 0 << endl;
    }
    else if (num == 2)
    {
        cout << "the " << num << " fibo num is " << 1 << endl;
    }
    else
    {
        for (int y = 0; y < num - 2; y++)
        {
            // get new fibo value

            x = list[y] + list[y + 1];
            for (int z = 2; z < num; z++)
            {
                // will append new value to the list

                list[z] = x;
            }
        }
        cout << "the " << num << " fibo num is " << list[-1] << endl;
        // get the last value which is the fibo value
    }
}

int main()
{
    fibonacci();

    return 0;
}

Solution

  • There is some inconsistent indexing here. If num = 1, the fibonacci number is 0, and if num=2, the fibonacci number is 1... but this does not quite match the declaration int list[num] = {0,1}, as indexes start with 0.

    I have rewritten the code so that the first number has an index of 1 (list[1]=0 and list[2]=1)

    A nested-for loop is not needed to append the new sum at the end of the array. Just a simple for loop will do.

    I have modified your code below, see below.
    
    #include <iostream>
    #include <cctype>
    #include <cmath>
    using namespace std;
    
    int fibonacci(){
       cout<<"enter sequence num: "<<endl;
       int num;
       cin>>num;
       int list[num];
       list[1] = 0;
       list[2] = 1;
       int x;
    
       if(num==1){
           cout<<"the "<<num<<" fibo num is "<<0<<endl;
       }else if(num==2){
           cout<<"the "<<num<<" fibo num is "<<1<<endl;
       }else{
           for(int y=3;y<=num;y++){ 
                  list[y]=list[y-1]+list[y-2];
           }
       }
       cout<<"the "<<num<<" fibo num is "<<list[num]<<endl; 
       
    }
    
    int main()
    {
       fibonacci();
       return 0;
    } 
    

    Hope this helps.