Write a java program to output the Fibonacci series using loop or recursion.

Fibonacci series is the series which start from 0 as the first element and 1 as the second element and the rest of the nth term is equal to (n-1)th term + (n-1)th term.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 …

So we in order to implement this, we need to do the following

  1. Take input ‘n‘ from the user which denotes the number of terms in Fibonacci series.
  2. Assign first element a=0 and second element b=1 and third element c = 0.
  3. Output the first two element and loop from 3 to n.
  4. Update c=a+b, a=b and b=c and output the value of c. Reapeat the same steps for each iteration.

Let’s print the Fibonacci series in java using the same steps mentioned above.

Fibonacci Seiries using Loop


Fibonacci Seiries using Recursion


In the above program, we are computing and returning the nth term of Fibonacci series from the recursive function. In each recursive call, we are doing the same calculation over again as done for the (n-1)th term. So recursive way of finding the Fibonacci term is not efficient.

To optimize it we can use dynamic programming for Fibonacci series.

If you have any suggestion or doubts then please comment below.

Leave a Reply

Close Menu