Sunday, 12 July 2015

fibonacci series in java

Fibonacci series implementation in java is frequently asked question in interview at fresher level. Moreover, it is a very famous example to show how to use recursive function in java.


public class Fibonacci {

    public static void main(String[] args){
        fibonacci(15);
    }
    
    /**
     * This method is used to print fibonacci series
     * @param n is total number of elements
     */
    private static void fibonacci(int n){
        for(int i = 0 ; i < n; i ++){
            System.out.print(fib(i)+", ");
        }
    }
    /**
     * This method is used recursively to find fibonacci
     * element at nth index. 
     * @param n is index
     * @return element
     */
    private static int fib(int n){
        if(n < 2)
            return n;
        return fib(n-1) + fib(n-2);
    }
}

Output : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377