Home / Data structures and Algorithms by Java Examples / Recursion / Fibonacci Series using Recursion in JAVA Example
Fibonacci Series using Recursion in JAVA Example
780 views.
FibonacciSeries.java
/*
 * Creating a program to print fibonacci series.
 */
class FibonacciSeries {
    
    /*
     * To perform fibonacci Series
     * fib(n) = fib(n-1) + fib(n-2)
     */
    public static int fib(int n) {
        //Base case: n < 2
        if (n < 2) {
            return n;
        }
        else {
            //Recursive case: fib(n) = fib(n-1) + fib(n-2)
            return fib(n-1) + fib(n-2);
        }
    }
    
    public static void main(String[] args) {
        //0 1 1 2 3 5 8 13 21 34
        
        //Running fibonacci series 0 to 9.
        for (int i = 0; i < 10; i++) {
            System.out.print(fib(i)+" ");
        }
    }
}
Output
0 1 1 2 3 5 8 13 21 34
Related Examples
   Simple Recursion Example in JAVA
   Print array using recursion JAVA Example
   Recursion on ArrayList Strings in JAVA Example
   Factorial Program using Recursion in JAVA Example
   Fibonacci Series using Recursion in JAVA Example
   Tree Traversal with Recursion in JAVA Example
   Tree Traversal without Recursion Using Stack Class in JAVA Example
   Is ArrayList Ordered using Recursion in JAVA Example
   Tower of Hanoi using Recursion in Java Example
Copyright © 2016 Learn by Examples, All rights reserved