Programming Examples

Java recursive function to find nth element of Fibonacci sequence


Write a Java Program to Create a Recursive function to find the Nth element of Fibonacci sequence.

The Fibonacci series can be generated as:

0,1,1,2,3,5,8,13,21,34....

The series start with first two terms 0 and 1 . The next term will be the sum of first two terms (i.e. 0+1=1). Next element is the sum of the elements of previous two terms (i.e. 1+1=2) and so on.

Solutions :

import java.util.*;
class FiboSeries
{
    int fib_nth(int n)
    {
        if(n==1)
        {
            return 0;
        }
        else
        {
            if(n==2)
                return (1);
            else
                return (fib_nth(n-2)+(fib_nth(n-1)));
        }
    }
    public static void main(String arr[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Any Term Number ");
        int num=sc.nextInt();
        FiboSeries obj=new FiboSeries();
        int ans=obj.fib_nth(num);
        System.out.println(num+" term of Fibonacci series is : "+ans);        
    }
}
Output

Enter Any Term Number 

9

9 term of Fibonacci series is : 21

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz