Fibonacci using dynamic programming

how this code is working

class fibonacci
{
static int fib(int n)
{
/* Declare an array to store Fibonacci numbers. */
int f[] = new int[n+2]; // 1 extra to handle case, n = 0
int i;

/* 0th and 1st number of the series are 0 and 1*/
f[0] = 0; 
f[1] = 1; 
  
for (i = 2; i <= n; i++) 
{ 
   /* Add the previous 2 numbers in the series 
     and store it */
    f[i] = f[i-1] + f[i-2]; 
} 
   
return f[n]; 
} 
   
public static void main (String args[]) 
{ 
    int n = 9; 
    System.out.println(fib(n)); 
} 

}

Hi @radhagovinda008

you have to find fibonacci series till n.Now as we know that the first element in fibonacci series is always 0 and the second element is 1,now when we calculate the 3 element it will be 0+1 =1 and fourth element will be 1+1=2 and so on.so we have made array of size n+2 and already fixed the value of f[0]=0 and f[1]=1 now in the loop we start from i=2 and calculate f[i]=f[i-1]+f[i-2](ie the element at 2 index is equal to sum of element at first index and element at 0th position and like this you go till n and return the array f.

thank you…
can you please explain this line
"int f[] = new int[n+2]; "
what I understood that the extra two is used for storing 0th and the 1st element of Fibonacci
but why ‘n’ doesn’t include the 1st two elements of Fibonacci in the first place why it is excluded

Hi ,it is just to store the 0th element test case.in this we are storing the ith element in ith index only so if we want to find the 5th element say then we have to make array of n+1 size and one i extra to store 0 th element .