Fibonacci Series Java

  1. /*

  2. Fibonacci Series Java Example

  3. This Fibonacci Series Java Example shows how to create and print

  4. Fibonacci Series using Java.

  5. */

  6.  

  7. public class JavaFibonacciSeriesExample {

  8.  

  9. public static void main(String[] args) {

  10.  

  11. //number of elements to generate in a series

  12. int limit = 20;

  13.  

  14. long[] series = new long[limit];

  15.  

  16. //create first 2 series elements

  17. series[0] = 0;

  18. series[1] = 1;

  19.  

  20. //create the Fibonacci series and store it in an array

  21. for(int i=2; i < limit; i++){

  22. series[i] = series[i-1] + series[i-2];

  23. }

  24.  

  25. //print the Fibonacci series numbers

  26.  

  27. System.out.println("Fibonacci Series upto " + limit);

  28. for(int i=0; i< limit; i++){

  29. System.out.print(series[i] + " ");

  30. }

  31. }

  32. }

  33.  

  34. /*

  35. Output of the Fibonacci Series Java Example would be

  36. Fibonacci Series upto 20

  37. 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

  38. */

0 comments: