Write a program to print Fibonacci series in Java using recursion?
Image of Write a program to print fibonacci series in java using recursion ? |
Java program to print the Fibonacci series using recursion:
java
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 for Fibonacci series: ");
int count = scanner.nextInt();
scanner.close();
System.out.println("Fibonacci series up to " + count + " terms:");
for (int i = 0; i < count; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
In this program:
- We prompt the user to enter the number of terms they want in the Fibonacci series.
- We then use a `for` loop to iterate through each term and print the Fibonacci number corresponding to that term using the `fibonacci()` method.
- The `fibonacci()` method is a recursive function that calculates the Fibonacci number for a given term. It checks if the term is either 0 or 1, and if so, returns the term itself. Otherwise, it recursively calls itself with `n - 1` and `n - 2` to calculate the Fibonacci number for the current term.
Post a Comment