2
int evenFibonacciSum(int max)
{
    int fib[max + 2];
    int i;

    fib[0] = 0;
    fib[1] = 1;

    for (i = 2; i <= max; i++)
        fib[i] = fib[i - 1] + fib[i - 2];

    return fib[max];
}

I am trying to write a function that will return the result of the Fibonacci sequence up until a max point. The issue is the compiler is saying that max must have a constant value when declaring the array. How can I fix this?

2 Answers2

1

Realize that you only ever need to keep track of three numbers and implement the function without the need of an array:

int fibonacci(int max)
{
    if (max < 2)
        return max;

    int a = 1;
    int b = 1;
    int c;
    int result = 1;

    for (int i = 0; i < max - 2; i++) {
        switch (i % 3) {
        case 0:
            result = c = b + a;
            break;
        case 1:
            result = a = c + b;
            break;
        case 2:
            result = b = c + a;
            break;
        }
    }

    return result;
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
1

You've encountered the reason for the existence of what we know as Dynamic Array or STL-Vectors.

The reason why compiler throws that error is due to that fact that in a standard array implementation the array size must be exactly specified during declaration.

float a[100] <- correct
float a[] <- incorrect

It is correct because the compiler exactly knows how much memory of a particular data type must be assigned to this array collection.

Now let's move onto the Dynamic Array - Raw pointers and STL Vector which gives you the privilege to decide the Array Size in runtime.

Method 1: Raw pointers

#include <cstddef> // std::size_t

int evenFibonacciSum(int max)
{
    int *fib=NULL;

    fib = new int[max+2];

    fib[0] = 0;
    fib[1] = 1;

    for (std::size_t i = 2; i <= max; i++)
        fib[i] = fib[i - 1] + fib[i - 2];

    int result = fib[max];
    delete [] fib;
    return result;
}

Method 2: STL Vectors

#include <cstddef>
#include <vector>

int evenFibonacciSum(int max)
{
    std::vector<int> fib(max+2);

    fib[0] = 0;
    fib[1] = 1;

    for (std::size_t i = 2; i <= max; i++)
        fib[i] = fib[i - 1] + fib[i - 2];

    return fib[max];
}

I would suggest you use Method 2: STL Vectors since it automatically takes care of the memory management issues that arises with such dynamic allocation.

Have a great day!

Arul Verman

Swordfish
  • 12,971
  • 3
  • 21
  • 43
Arul Verman
  • 43
  • 1
  • 7