This is the second solution to find the nTh number of the Fibonacci series using recursion approach.
import java.util.Scanner;
public class NthFibonacciRecursion {
public static void main(String[] args) {
Scanner number=new Scanner(System.in);
// To find the nTh number of Fibonacci series, read nTh value here
System.out.println("Enter nTh number=");
int nTh=number.nextInt();
number.close();
//Call the function nthFib() with nth value as parameter
System.out.println("The "+nTh+"th value of the Fibonacci series is "+ NthFib(nTh-1));
}
private static int NthFib(int nthNum) {
// Exit criteria of this recursive function when the parameter value reaches 0 or 1.
if (nthNum == 0 || nthNum == 1)
return nthNum;
else
/* Recursive calls to NthFib() with n-1 and n-2 as a parameter values. The following recursive calls will update the parameter values as per the Fibonacci series logic */
return (NthFib(nthNum-1)+NthFib(nthNum-2));
}
}
OUTPUT:
Enter nTh number=
20
The 20th value of the Fibonacci series is 4181

Leave a comment