Java Online Compiler
Example: Fibonacci Series using Recursion in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Fibonacci Series using Recursion import java.util.Scanner; // Main class containing the entry point of the program public class Main { // Recursive function to calculate the nth Fibonacci number public static int fibonacci(int n) { // Base cases if (n <= 1) { return n; } // Recursive step return fibonacci(n - 1) + fibonacci(n - 2); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Prompt user for the number of terms System.out.print("Enter the number of terms (n): "); int n = scanner.nextInt(); // Step 2: Validate input if (n < 0) { System.out.println("Number of terms cannot be negative."); } else { // Step 3: Print the Fibonacci series System.out.println("Fibonacci Series up to " + n + " terms:"); for (int i = 0; i < n; i++) { System.out.print(fibonacci(i) + " "); } System.out.println(); // For a new line at the end } scanner.close(); } }
Output
Clear
ADVERTISEMENTS