×

# Java program to print the Fibonacci series using recursion

Java example to print the Fibonacci series using recursion.
Submitted by Nidhi, on June 01, 2022

## Problem statement

In this program, we will read the number of terms from the user, and then we will print the Fibonacci series using recursion.

## Source Code

The source code to print the Fibonacci series using recursion is given below. The given program is compiled and executed successfully.

```// Java program to print the Fibonacci series
// using the recursion

import java.util.*;

public class Main {
public static void getFibonacci(int a, int b, int term) {
int sum;

if (term > 0) {
sum = a + b;
System.out.printf("%d ", sum);

a = b;
b = sum;

getFibonacci(a, b, term - 1);
}
}

public static void main(String[] args) {
Scanner X = new Scanner(System.in);
int a = 0;
int b = 1;
int sum = 0;
int term = 0;

System.out.printf("Enter total number of terms: ");
term = X.nextInt();

System.out.printf("Fibonacci series is : ");
System.out.printf("%d\t%d ", a, b);

getFibonacci(a, b, term - 2);
}
}
```

### Output

```Enter total number of terms: 10
Fibonacci series is : 0 1 1 2 3 5 8 13 21 34
```

## Explanation

In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main. The Main class contains two static methods getFibonacci(), and main(). The getFibonacci() is a recursive method that prints the Fibonacci series.

The main() method is the entry point for the program. Here, we read terms for the Fibonacci series from the user and called the getFibonacci() method and printed the Fibonacci series.