Search code examples
c++fibonaccilvalue

error C2106: '=' : left operand must be l-value in Fibonacci sequence by dynamic programming in C++


I am trying to write a program for generating Fibonacci sequence by dynamic programming approach as follows.

#include<iostream>
#include<ctime>

int fib(int index)
{
    int memo[] = {0};
    memo[0] = 0;
    memo[1] = 1;
    for(int i = 2; i <= index; i++)
    {
        fib(index) = fib(index - 1) + fib(index - 2);   //error comes here
    }
    return fib(index);
}
int main()
{   
    time_t start, end, diff;
    int index;
    std::cout << "Please, enter the index of fibonacci sequence" << std::endl;
    std::cin >> index;
    start = time(NULL);
    std::cout << "calculating...." << std::endl << fib(index) <<std::endl;
    end = time(NULL);
    diff = (time_t)difftime(end, start);
    std::cout << "Time elapsed: " << diff << std::endl;
    return 0;
}

But, in the line fib(index) = fib(index - 1) + fib(index - 2); Iam getting error as

error C2106: '=' : left operand must be l-value

So, please tell me what's wrong I have done in that line. Thanks in advance.


Solution

  • You're assigning to an l-value (which is what int fib(int) returns). Just like the error message states.

    Also note that int memo[] = {0}; creates an array of size 1, so writing beyond index 0 is invalid.