Fibonacci Series Program in Java using Recursion

Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1. Thus, we will get the series as 0, 1, 1, 2, 3, 5, 8, ……

We get the third term as 1 because its previous two terms are 0 and 1. The fourth term is 2 because its previous two terms are 1 and 1 and so on. Again, we will be discussing both the iterative as well as the recursive approach. Let us start with the iterative one.

Iterative Approach

Filename: FibonacciExample.java

Output:

Explanation: The above approach is quite easy. First, we are initializing the first two terms of the series (a = 0 and b = 1). In the first two iterations, we are printing the first two terms. From the third iteration onwards, we are calculating the next term, printing it, and then updating the last two terms to get prepared for the next iteration. Now, let us discuss the recursive approach.

Recursive Approach

Filename: FibonacciExample1.java

Output:

Explanation: We have seen that every term in the Fibonacci series is dependent on last two terms. Thus, if we define a function F(n) which gives the value of the nth term of the series, we get our recursion relation as:

On the basis of the above relation, we have written our recursion method findFibonacci(). The if condition in the findFibonacci() method takes care of the base case: first term = 0 and second term = 1. Thus, we have:

findFibonacci(0) = 0

findFibonacci(1) = 1

findFibonacci(2) = findFibonacci(0) + findFibonacci(1) = 0 + 1 = 1

findFibonacci(3) = findFibonacci(2) + findFibonacci(1) = 1 + 1 = 2

findFibonacci(4) = findFibonacci(3) + findFibonacci(3) = 2 + 1 = 3

findFibonacci(5) = findFibonacci(4) + findFibonacci(3) = 3 + 2 = 5

Displaying Fibonacci Series Up to A Given Number

So far, we have only discussed to display the Fibonacci series up to given term (up to 6th term in our examples). However, we can also display the series up to a given number. The following example illustrates the same.

Filename: FibonacciExample2.java

Output:

Explanation: Here, we limited our display up to number 50 by checking the last term is less than or equal to 50 or not in the while loop.

Pin It on Pinterest

Share This