The Fibonacci sequence is defined by the following rule: The fist two values in the sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it. Write a Java program that uses both recursive and non recursive functions to print the nth value in theFibonacci sequence.

//Program to print nth value in the fibonacci series
import java.util.*;
class Function
{         
            void nrcf(int a,int b,int c,int n)
            {
                        for(int i=1;i<=n-2;i++)
                        {
                                    c=a+b;
                                    a=b;
                                    b=c;
                        }
                        a=b=1;
                        System.out.println(“nth value in the series using non recursive function is : “+c);
                       
            }
            void  rcf(int a,int b,int c,int n)
            {
                                   
                        if(n-2>0)
                        {
                                    c=a+b;
                                    a=b;
                                    b=c;
                                    rcf(a,b,c,n-1);
                                    return;
                        }
                       
                        System.out.println(“nnth value in the series using recursive function is : “+c);
            }
}
           
class Fibonacci
{
            public static void main(String args[])
            {
                        Function f=new Function();
                        int n,a=1,b=1,c=0;
                        Scanner scr=new Scanner(System.in);
                        System.out.println(“nEnter n value:  “);
                        n=scr.nextInt();
                        f.nrcf(a,b,c,n);
                        f.rcf(a,b,c,n);
                       
            }
}
Output:
Enter n value:
10
nth value in the series using non recursive function is : 55

nth value in the series using recursive function is : 55

Leave a Reply

Your email address will not be published. Required fields are marked *

Enable Notifications OK No thanks