0% found this document useful (0 votes)
5 views1 page

FIBONACCI

The document contains a Java program that calculates the nth Fibonacci number using a recursive method. It prompts the user to enter a non-negative integer and validates the input before computing and displaying the corresponding Fibonacci number. The program includes base cases for Fibonacci(0) and Fibonacci(1) and handles user input through a Scanner object.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

FIBONACCI

The document contains a Java program that calculates the nth Fibonacci number using a recursive method. It prompts the user to enter a non-negative integer and validates the input before computing and displaying the corresponding Fibonacci number. The program includes base cases for Fibonacci(0) and Fibonacci(1) and handles user input through a Scanner object.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import java.util.

*;
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);
}
}
}

You might also like