Java week1 :Fibonacci series
by Shivu on Mar.19, 2010, under Uncategorized
b) 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 the Fibonacci sequence.
import java.lang.*;
/**
*fibonacci**/
class Fibonacci
{
public int nthfiborec(int n)
{
if (n==1||n=0)
return 1;
else
return (nthfiborec(n-2)+nthfiborec(n-1));
}
public int nthfibo(int no)
{
int fib=0,num1=1,num2=1;
for(int counter = 1; counter <= no-2; counter++)
{
fib=(num1 + num2);
num1=num2;
num2=fib;
}
return fib;
}
}
class Mfibonacci
{
public static void main(String args[])
{
Fibonacci f=new Fibonacci();
BufferedReader Br=new BufferedReader( new InputStreamReader(System.in));
System.out.print("Enter a number:");
int n=Integer.pareseInt(br.readLine());
System.out.println("The"+n+"th term of fibonacci series is "+f.nthfibo(n));
System.out.println("The"+n+"th term of fibonacci series using recursion is "nthfibo(n-1));
}
System.out.println("k="+k);
}