Pages

Ads 468x60px

Monday 17 December 2012

Recursive and non-Recursive fibonacci series



      1.      The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are 1, 1. Every subsequent value is the sum of the 2 values preceding it. Write A Java Program (WAJP) that uses both recursive and non-recursive functions to print the nth value of the Fibonacci sequence.

                                                         download link for fibonacci
      Program for recursive fibonacci:
      class Fibonacci
{
  public static long fib(int n)
  {
   if(n<=1)
   
     return 1;
   else
   
    return fib(n-1)+fib(n-2);
  }
  public static void main(String[] args)
  {
   int n=Integer.parseInt(args [0]);
  
    for(int i=1;i<=n;i++)
   
     System.out.println(i+":"+fib(i));
  }
}      
     
     Program for non-recursive:
     class Fibonacci
{
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
System.out.println("fibonacci series");
int f1,f2=0,f3=1;
for(int i=1;i<=n;i++)
{
System.out.println(""+f3+"");
f1=f2;
f2=f3;
f3=f1+f2;
}
}
}
     


0 comments:

Post a Comment

 

Sample text

Sample Text

Sample Text