Here’s a simple program in Java to generate the Fibonacci series:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Scanner; public class FibonacciSeries { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of terms in the series: "); int n = scanner.nextInt(); scanner.close(); int firstTerm = 0, secondTerm = 1; System.out.println("Fibonacci series up to " + n + " terms:"); // Print the first two terms System.out.print(firstTerm + " " + secondTerm); // Generate and print the remaining terms for (int i = 3; i <= n; i++) { int nextTerm = firstTerm + secondTerm; System.out.print(" " + nextTerm); // Update the values for the next iteration firstTerm = secondTerm; secondTerm = nextTerm; } } } |
Explanation:
- The program asks the user to enter the number of terms they want in the Fibonacci series.
- The first two terms of the series,
firstTerm
andsecondTerm
, are initialized as 0 and 1 respectively. - The program then prints the first two terms.
- Using a
for
loop, the program generates and prints the remaining terms of the series. - In each iteration, the next term is calculated by adding the previous two terms (
firstTerm
andsecondTerm
). - The values of
firstTerm
andsecondTerm
are updated for the next iteration. - 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Scanner; import java.util.stream.Stream; public class FibonacciSeries { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of terms in the series: "); int n = scanner.nextInt(); scanner.close(); System.out.println("Fibonacci series up to " + n + " terms:"); Stream.iterate(new int[] { 0, 1 }, fib -> new int[] { fib[1], fib[0] + fib[1] }) .limit(n) .map(fib -> fib[0]) .forEach(fib -> System.out.print(fib + " ")); } } |
Explanation:
- The program asks the user to enter the number of terms they want in the Fibonacci series.
- Using the
Stream.iterate
method, we start with an initial seed value of[0, 1]
. - The lambda expression
fib -> new int[] { fib[1], fib[0] + fib[1] }
generates the next Fibonacci number by adding the previous two numbers. - We limit the stream to
n
terms using thelimit
method. - We map each Fibonacci pair to the first element
fib[0]
using themap
method. - 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.