Java Code to Compute Fibonacci Series using Recursion for N Terms.

/* Fibonacci Numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34…. which can be calculated by the formula fn=fn-1+fn-2 where f1=1, f2=1.
Fibonacci series is a sequence of numbers defined by f1 = 1 f2 = 1 fn=fn-1+fn-2The following code prints Fibonacci series for N terms (Fibo(n)) using recursion . */

import java.io.*;

public class FiboSeries
{
public static void main(String[] args)
{

System.out.println(“Enter the no of terms the Fibonacci Series to be generated”);

try
{
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));

int n = Integer.parseInt(br.readLine());

System.out.println(“Fibonacci Series upto “+ n + ” Terms”);
for (int i = 1; i <= n; i++)
{
int f = fibo(i);
System.out.print(f +” “);
}
}

catch (Exception e)
{
System.out.println(“Error”);
}

System.exit(0);
}

//to find nth Fibonacci number
public static int fibo(int n)
{
if (n <= 2)
return 1;
else
return fibo(n – 1) + fibo(n – 2);
}
}

Output of the Above Program
———————————-
Enter the no of terms the Fibonacci Series to be generated
10
Fibonacci Series upto 10 Terms
1 1 2 3 5 8 13 21 34 55

You may also like

Leave a Reply