We’ll discuss Fibonacci series using recursion and non-recursion approach with logic, and code example in java and code explanation.
If you’re not familiar about the Fibonacci series, here’s the brief or you can skip:
The Fibonacci series is a sequence of numbers in which each number after the first two is the sum of the two preceding ones.
It is defined as follows:
F(0) = 0 F(1) = 1 F(n) = F(n-1) + F(n-2) for n > 1
So, the first few terms of the Fibonacci series are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …
Fibonacci series in java using recursion
The Fibonacci series can also be implemented using recursion in Java. In this approach, the function calls itself with smaller values of n
until it reaches the base case (i.e., n=0
or n=1
), and then returns the value of n
.
Here’s an example code that implements the Fibonacci series using recursion in Java:
public class FibonacciSeriesRecursive {
public static void main(String[] args) {
int n = 10;
System.out.print("Fibonacci Series of "+n+" terms:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n-1) + fibonacci(n-2);
}
}
In this code, we define a recursive function fibonacci()
that takes an integer n
as input and returns the n
th term of the Fibonacci series.
The base case is when n
is either 0
or 1
, and in that case, the function simply returns n
. Otherwise, the function recursively calls itself with the arguments n-1
and n-2
, and returns the sum of the two resulting values.
In the main()
method, we first define the number of terms to generate as n
. We then use a loop to call the fibonacci()
function with values of i
from 0
to n-1
, and print the resulting values.
When we run this code, it will generate the first 10 terms of the Fibonacci series:
Fibonacci Series of 10 terms:0 1 1 2 3 5 8 13 21 34
Note that the recursive approach is less efficient than the iterative approach we showed earlier, as it involves repeated function calls and redundant calculations.
Fibonacci series in java using non-recursion
For the Fibonacci series printing using non recursion method, in other words, Fibonacci series using iterative approach, you can read this post.