Wednesday, December 14, 2016

Fibonacci Series

Fibonacci Series = 0 1 1 2 3 5 8 13 21 34.

Basically we have to add the previous and current number to get the next number.


Java Code->
public class Fibonacci
{
    static int[] fibonacci(int n)
    {
     //Declare an array to store Fibonacci numbers
     int f[] = new int[n+1];
     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; //Return the array back to main method.
    }

 
   public static void main(String[] args)
   {
     int n = 9;
     int[] ans = fibonacci(n);
 
     for (int i = 0; i <= n; i++)
     {
        System.out.print(ans[i]+" "); //Print the array.
     }
   }

}

No comments:

Post a Comment

Home