FIBONACCI
FIBONACCI
*;
public class FibonacciCalculator
{
// Recursive method to calculate the nth Fibonacci number
public static int fibonacci(int n)
{
if (n == 0)
{
return 0; // Base case: F(0) = 0
}
else if (n == 1)
{
return 1; // Base case: F(1) = 1
}
else
{
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}
}
public static void main()
{
// Create a scanner object to take input from user
Scanner sc = new Scanner(System.in);
// Ask the user for input
System.out.print("Enter a non-negative integer: ");
int num = sc.nextInt();
// Ensure the number is non-negative
if (num < 0)
{
System.out.println("Please enter a non-negative integer.");
}
else
{
// Call the recursive Fibonacci method and display the result
int result = fibonacci(num);
System.out.println("The " + num + "th Fibonacci number is " + result);
}
}
}