Fibonacci Series Program in Java using Recursion

In this tutorial we are going to learn how to print Fibonacci series in java program using recursion.

Read this: What is Fibonacci Series? Fibonacci series program in C using recursion.

How this Java program will behave?

Its Logic is different from Fibonacci series program in Java using iteration.

Here we have a function named fibonacci()  which is recursive. Each time it will call itself to calculate the elements of the series. 

This Fibonacci series program will take integer as input. And print series upto given input.

Suppose if someone has given 6 as input, output will be

0, 1, 1, 2, 3, 5

Program 1: Fibonacci Series using Recursion in Java

import java.util.*;  
class Main{
    public static void main(String ...a){
        int i, k; 
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter number- ");  
        int n= sc.nextInt();
        System.out.println("fibonacci series is: "); 
	    for(i=0;i<n;i++) { 
		    System.out.println(Main.fibonacci(i));
	    }
    }
    static int fibonacci(int i){ 
	    if(i==0) return 0; 
	    else if(i==1) return 1; 
	    else return (fibonacci(i-1)+fibonacci(i-2));
    }
} 

Output:

Enter number- 4
fibonacci series is: 
0
1
1
2

Conclusion

In this tutorial, we have learnt the writing and implementation of the Fibonacci series in Java using a recursive approach. The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.

Key Aspects:

  1. Recursive Approach:
    • In the above Java program we have a recursive method to calculate and print the Fibonacci series.
    • A recursive function named fibonacci is defined, which calls itself to compute each element in the series.
  2. User Input:
    • The program takes an integer input (n) from the user. This n is basically the number of elements in series to print.
  3. Function Logic:
    • The fibonacci function serves as the recursive engine, calculating the Fibonacci value for each position in the series. Our recursive call is (fibonacci(i-1)+fibonacci(i-2)).
    • The base cases (i == 0 and i == 1) are handled to return 0 and 1, respectively.
  4. Output :
    • The output prints the Fibonacci series: 0, 1, 1, 2 after generating.

Happy coding! 🚀

Leave a Comment