Java Program to Print Fibonacci Series with and without using Recursion

  • Write a program in Java to print Fibonacci series without recursion.
  • How to generate Fibonacci series using recursion.

Fibonacci series is a series of integers, where Nth term is equal to the sum of N-1th and N-2th(last two terms). The first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent term is the sum of the previous two terms.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ....


Java program to generate fibonacci series

Algorithm to generate fibonacci series
  • First two terms of fibonacci series is 0 and 1.
  • we will store the last two terms of fibonacci series in "last" and "secondLast" integer variable.
  • Current term of fibonacci series is equal to the sum of "last" and "secondLast" term.(current = last + secondLast)
  • Update last and secondLast variable as secondLast = last; and last = current;
package com.tcc.java.programs;

import java.util.*;

public class FibonacciSeries {
    public static void main(String args[]) {
        int terms, last = 1, secondLast = 0, current, i;

        Scanner in = new Scanner(System.in);
        System.out.println("Enter number of terms in Fibonacci Series");
        terms = in.nextInt();

        /*
         *  Nth term = (N-1)th thrm + (N-2)th term;
         */
        for(i = 0; i < terms; i++){
            if(i < 2){
                current = i;
            } else {
                current = last + secondLast;
                secondLast = last;
                last = current;
            }
            System.out.print(current + " ");
        }
    }
}
Output
Enter number of terms in Fibonacci Series
10
0 1 1 2 3 5 8 13 21 34

Java program to print fibonacci series using recursion

In mathematical terms, the Nth term of Fibonacci series is defined by the recurrence relation:

  • fibonacci(N) = Nth term in fibonacci series
  • fibonacci(N) = fibonacci(N - 1) + fibonacci(N - 2);
  • whereas, fibonacci(0) = 0 and fibonacci(1) = 1

In this program, we will write a user defined recursive function "int fibonacci(int N)" which returns Nth fibonacci number.

package com.tcc.java.programs;

import java.util.*;

public class FibonacciSeriesRecursion {
    public static void main(String args[]) {
        int terms, i;
  
       Scanner in = new Scanner(System.in);
       System.out.println("Enter number of terms in Fibonacci Series");
       terms = in.nextInt();

       /*
        * fibonacci(N) = fibonacci(N-1) + fibonacci(N-2);
        */
       for(i = 0; i < terms; i++){
           System.out.print(fibonacci(i) + " ");
       }
    }
 
    public static int fibonacci(int num){
        /* Exit condition of recursion*/
        if(num < 2)
            return num;
        return fibonacci(num - 1) + fibonacci(num - 2);
    }
}
Output
Enter number of terms in Fibonacci Series
12
0 1 1 2 3 5 8 13 21 34 55 89