Java Program to Display Fibonacci Series

In this post we will explore how to generate Fibonacci Series in java and understand the logic behind it.

Fibonacci Series:

In Fibonacci series, the next number is the sum of previous two numbers.
for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc.

Solutions:

There are two ways to display Fibonacci series in java

  • Fibonacci series using loop.
  • Fibonacci series using recursion.

Approach 1 : Fibonacci series using loop.

class FibonacciSeries {
    public static void main(String[] args) {
        int n = 10; 
        int num1 = 0; 
        int num2 = 1;
        System.out.print("Fibonacci Series of " + n + " numbers:");

        for (int i = 1; i <= n; ++i) {
            System.out.print(num1 + " ");

            int sum = num1 + num2;
           num1 = num2;
           num2 = sum;
        }
    }
}

Output:

Fibonacci Series of 10 numbers:0 1 1 2 3 5 8 13 21 34

Approach 1 : Fibonacci series using recursion

class Fibonacci {
    static int fib(int n) {
        if (n <= 1)
            return n;
        return fib(n - 1) + fib(n - 2);
    }

    public static void main(String[] args) {
        int n = 10;
        System.out.print("Fibonacci Series of " + n + " numbers:");

        for (int i = 0; i < n; i++) {
            System.out.print(fib(i) + " ");
        }
    }
}


Output:

Fibonacci Series of 10 numbers:0 1 1 2 3 5 8 13 21 34

More Java Programs:

 

Leave a Comment

%d bloggers like this:
Python4U
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.