Nth number in the Fibonacci series
Write a Java program to find the Nth number in the
Fibonacci series using recursion.
package Fibonacciseries;
import
java.util.Scanner;
public class
NthFibonacciSeries
{
public static int
findNthFibonacci(int n)
{
if (n <= 0)
{
throw new
IllegalArgumentException("N must be a positive integer.");
}
if (n == 1) {
return 0;
} else if (n == 2) {
return 1;
} else {
return findNthFibonacci(n - 1) + findNthFibonacci(n - 2);
}
}
public static void main(String[] args) {
Scanner
scObj= new Scanner(System.in);
System.out.print("Enter Any
number = ");
int n = scObj.nextInt(); // Replace this
with the desired Nth number
int result = findNthFibonacci(n);
System.out.println("The
"
+ n + "th number
in the Fibonacci series is: " + result);
}
}
Output :
Enter Any number = 11
The 11th number in the Fibonacci series is: 55
Explanation :
1. The findNthFibonacci method is a recursive function that takes the parameter n, which represents the position of the number to be found in the Fibonacci series.2. We first check if n is less than or equal to 0. If it is, we throw an IllegalArgumentException because the Fibonacci series is only defined for positive integers.
3. Next, we handle the base cases for n = 1 and n = 2, as the first two numbers in the Fibonacci series are 0 and 1, respectively.
4. For n > 2, we recursively call the findNthFibonacci method with n - 1 and n - 2 to find the two preceding numbers in the series. We then return the sum of these two numbers, which gives us the Nth number in the Fibonacci series.
5. In the main method, we specify the value of n to find the Nth number in the Fibonacci series and then print the result.
Comments
Post a Comment