Search Tutorials

Tuesday 23 April 2013

Java code to generate Fibonacci series using recursion

Java program to generate Fibonacci series containing given number of terms using recursion.

import java.io.*;
class Fibonacci
{
 public static void main(String args[]) throws IOException
 {
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 Fibonacci call = new Fibonacci();
 System.out.print("Enter no. of terms : ");
 int n = Integer.parseInt(br.readLine());
 call.generate(n);
 }
 int fibo(int n)
 {
 if(n==1)
  return 1;
 else if(n==2)
  return 1;
 else
  return fibo(n-2)+fibo(n-1);
 }
 void generate(int n)
 {
 for(int i=1;i<=n;i++)
  System.out.println(fibo(i));
 }
}

ALGORITHM:-

1. Start

2. Accept the number of terms of the Fibonacci series from the user.

3. A particular term of the series is the sum of its previous two terms.

4. Using method recursion generate the terms of the series.

5. Print the Fibonacci series up to the number of terms as required by the user.

No comments:

Post a Comment

Back to Top