Saturday, June 23, 2018

How do you print Fibonacci series?

Problem statement: How do you print Fibonacci series?

Def: A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers.
  1. public class FibonacciSeries {
  2. public static void main(String[] args) {
  3. int count = 10;
  4. printFibonacci(count);
  5. }
  6. public static void printFibonacci(int count) {
  7. int a = 0, b = 1, c = 0;
  8. System.out.print(a + " " + b + " ");
  9. for (int i = 2; i < count; i++) {
  10. c = a + b;
  11. a = b;
  12. b = c;
  13. System.out.print(c + " ");
  14. }
  15. }
  16. }
Output: 
0 1 1 2 3 5 8 13 21 34

Method-II:
  1. public class FibonacciSeries {
  2. public static void main(String[] args) {
  3. fibonacci(10); // 10 is count 
  4. }
  5. public static void fibonacci(int n) {
  6. int a[] = new int[n];
  7. a[0] = 0;
  8. a[1] = 1;
  9. System.out.print(a[0] + " " + a[1] + " ");
  10. for (int i = 2; i < n; i++) {
  11. a[i] = a[i - 1] + a[i - 2];
  12. System.out.print(a[i] + " ");
  13. }
  14. }
  15. }
Output:
0 1 1 2 3 5 8 13 21 34

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...