Fibonacci Series Using Recursion in Java
Q. Write a Java program to generate Fibonacci Series using recursion
import java.util.Scanner;
public class FibonacciRecursive {
// Recursive method to return the nth Fibonacci number
public static int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Ask user for the number of terms
System.out.print("Enter the number of terms: ");
int n = scanner.nextInt();
System.out.println("Fibonacci Series using recursion:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
scanner.close();
}
}
Q. Write an algorithm to generate Fibonacci Series using recursion
1. Start
2. Define a recursive function fibonacci(n)
If n == 0, return 0
If n == 1, return 1
Else, return fibonacci(n - 1) + fibonacci(n - 2)
3. Read an integer n (number of terms)
4. Loop from i = 0 to n - 1 and print fibonacci(i)
5. End
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com