#include<iostream>
using namespace std;
long long int memo[20] = {-1}; //create memo table and initialise to -1
long long int fibo(long long int n)
{
if(memo[n]>-1) //changing this to if(memo[n]>0) works fine
return memo[n]; //but as such this gives 0 from all my inputs
if(n<=2)
return 1;
memo[n] = fibo(n-1) + fibo(n-2); //recurse
return memo[n];
}
int main()
{
long long int n;
cin>>n;
cout<<fibo(n)<<endl; //calls the fibo function
for(int i=0;i<20;i++) //this prints my memo table used...
cout<<memo[i]<<" ";
}
I am calculating the nth Fibonacci number using top-down dp but my memo table is zeroed out. Even at locations which I am not touching, why?
When you have
long long int memo[20] = {-1};
You are not telling the compiler to initialize the array with all -1. What you are telling it is here is a initializer list and initialize the elements in the array with its contents. Since the list is smaller than the array every missing initializer causes the compiler to zero initialize the corresponding elements.
Because that's how array initialization works in C++. You set the first element of the array memo
to -1
, and the compiler will value-initialize (before the C++11 standard) or default-initialize (since C++11 and onward) all of of the other elements.
Please read more about aggregate initialization here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With