Sam
Sam

Reputation: 71

Calculating Fibonacci Numbers in C++ code

My question is: I have a matrix. I need to calculate the corresponding Fibonacci number to each entry in that matrix, and return those values into another matrix. I keep getting a C2109 "Subscript requires array or pointer type", and I know where it's coming from, and I know what it means, but I don't know how to

  1. fix it
  2. make my code work.

Right now, it doesn't do anything. I'm not sure if I'm even returning any value from my Fibonacci function, or calling it correctly in my main function. I've modified it from what it originally was. Here's my new code:

const int     row1 = 3;
const int     col1row2 = 3;
const int     col2 = 3;

int fibonacci (int [][col2]);

void main()
{
     int   p[row1][col2],  f [row1][col2];
     int sum; 
     input (a,b); 

     cout<<"The Fibonacci Matrix is:   ";
     cout<<fibonacci(p);    
     for ( int  i = 0; i < row1; i++)
     {
          for ( int  j = 0; j < col2; j++)
              {
                    sum = f[i][j]; 
                    f[i][j] = fibonacci(p);           
              }
     }
     cout<<endl;
}


int fibonacci (int z[][col2])
{
     int   fib [100]  =  {0 , 1};
     int sum = 0;

     for ( int m = 2; m < 100; m++)
     {
           sum =  fib[m-1] + fib[m-2];
           fib[m] = sum;
     }
     return sum;
     cout<<endl;
}

Any help is appreciated!

Upvotes: 7

Views: 2284

Answers (2)

AndersK
AndersK

Reputation: 36082

In addition to what templatetypedef said you are only supplying one argument to the fib function but declared it to take two arguments. Also the fib() doesn't return a value - its declared void.

fib( p [i][j] );

There is a semicolon missing also here

sum = fib[ m - 1]  +  fib[ m - 2]

Upvotes: 2

templatetypedef
templatetypedef

Reputation: 372704

I think the problem is that this line:

f [i][j] = fib [ p [i][j] ];

Is trying to call the fib function incorrectly. You have the right idea here, but to call a function in C++ you need to use regular parentheses rather than square brackets. I think this line should look like

f [i][j] = fib ( p [i][j] );

As a follow-up, your implementation of fib seems like it might be incorrect. In particular, you're taking in two parameters corresponding to the matrices, but you never use those values directly. Instead, you're constructing a new local array of all the Fibonacci numbers. You will probably want to have this function return the appropriate Fibonacci number it generates.

Hope this helps, and best of luck on your journey into C++!

Upvotes: 4

Related Questions