B)
The
Fibonacci sequence is defined by the following rule:
The first 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 the Fibonacci sequence.
Program:
import java.io.*;
class Fibo
{
int nonRecursive(int n1)
{
int f3=0,f1=0,f2=1;
if(n1==0 || n1==1) return n1;
else
{
int count=2;
while(count<=n1)
{
f3=f1+f2;
f1=f2;
f2=f3;
count++;
}
return f3;
}
}
int recursive(int n1)
{
if(n1==0 || n1==1) return
n1;
else return recursive(n1-1)+recursive(n1-2);
}
public static void main(String args[])
throws IOException
{
int n;
Fibo ob=new Fibo();
BufferedReader br=new
BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter The
Value Of n: ");
n=Integer.parseInt(br.readLine());
System.out.println("RECURSIVE
METHOD");
System.out.println(+n+"th Value
In Fibonacci Sequence Is:"+ob.recursive(n));
System.out.println("\nNON
RECURSIVE METHOD ");
System.out.println(+n+"th Value
In Fibonacci Sequence Is:"+ob.nonRecursive(n));
}
}
Output:
E:\Lab>java
Fibo
Enter The Value
Of n: 5
RECURSIVE METHOD
5th Value In
Fibonacci Sequence Is:5
NON RECURSIVE
METHOD
5th Value In
Fibonacci Sequence Is:5