The Fibonacci sequence is defined by the following rules: 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 Code in JAVA:
import java.io.*;
import java.math.*;
class Fibonacci
{
int Fib(int n)
{
if(n==0)
return 0;
else if(n==1) return 1;
else
return Fib(n-1)+Fib(n-2);
}
}
class Fibrec
{
public static void main(String[] args) throws Exception
{
int n;
long r=0;
System.out.println("Enter N value:");
DataInputStream dis=new DataInputStream(System.in);
n=Integer.parseInt(dis.readLine());
Fibonacci f=new Fibonacci();
for(int i=1;i<=n; i++)
{
System.out.print(f.Fib(i)+"\t");
r=f.Fib(n);
}
System.out.println("\nThe "+n+" the value in the Fibonacci Series : "+r);
}
}

Program Output:
c:\java>javac Fibrec.java
c:\java>java Fibrec
Enter N value:
8
1 1 2 3 5 8 13 21 
The 8 the value in the Fibonacci Series : 21
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: