Fibonacci series program in java

If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.

Fibonacci series is numerical series in which next number is sum of previous two numbers.
For example :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc.
There are two ways to print Fibonacci series.

  • Using iteration
  • Using recursion

Using iteration:

Algorithm:

  • Initialise first two terms with 0 and 1
  • Find sum of first two terms.
  • Iterate upto numberOfElements
  • Print the sum
  • Assign prev to next and next to sum to go for next two terms.

Program:

When you run above program, you will get following output:

Using recursion:

Algorithm:

  • Initialise first two terms with 0 and 1
  • Base case will be when numberOfElements becomes 0.
  • Find sum of first two terms.
  • Print the sum
  • Assign prev to next and next to sum to go for next two terms.
  • Call same function again and decrease numberOfElements.

Program:

When you run above program, you will get following output:
Please go through java interview programs for more such programs.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *