Fibonacci Series in Java

Here’s a simple program in Java to generate the Fibonacci series:

Explanation:

  1. The program asks the user to enter the number of terms they want in the Fibonacci series.
  2. The first two terms of the series, firstTerm and secondTerm, are initialized as 0 and 1 respectively.
  3. The program then prints the first two terms.
  4. Using a for loop, the program generates and prints the remaining terms of the series.
  5. In each iteration, the next term is calculated by adding the previous two terms (firstTerm and secondTerm).
  6. The values of firstTerm and secondTerm are updated for the next iteration.
  7. The loop continues until the desired number of terms (n) is reached.

You can run this program and enter the number of terms you want in the Fibonacci series to see the output.

Here’s an implementation of the Fibonacci series using Java 8 features such as streams and lambda expressions:

Explanation:

  1. The program asks the user to enter the number of terms they want in the Fibonacci series.
  2. Using the Stream.iterate method, we start with an initial seed value of [0, 1].
  3. The lambda expression fib -> new int[] { fib[1], fib[0] + fib[1] } generates the next Fibonacci number by adding the previous two numbers.
  4. We limit the stream to n terms using the limit method.
  5. We map each Fibonacci pair to the first element fib[0] using the map method.
  6. Finally, we use the forEach method to print each Fibonacci number.

This implementation leverages the power of streams and lambda expressions to generate and print the Fibonacci series in a concise manner.

About Manohar

I, Manohar am the founder and chief editor of ClarifyAll.com. I am working in an IT professional.

View all posts by Manohar →

Leave a Reply