A Recursion is function which call itself. This enables the function
to repeat itself several times, outputting the result and the end of each
iteration.
A class Recursion has
been defined to find the Fibonacci series upto a limit. Some of the members
of the class are given below:
Class
Name : Recursion
Data Members/instance variables : f1, f2, fib, limit
Member functions/methods :
Recursion()
: constructor to assign f1,f2,fib with appropriate values.
void input()
: to accept the limit of the series.
int
fibo(int n) : to return the nth(limit0 Fibonacci term
using recursive technique.
void
genearate_fibseries() : to generate the Fibonacci series upto the given
limit.
Solution:
Recursive
method execute a little slower than the iterative method. Many recursive calls
to a method could cause a stack overrun. Because storage for parameters and
local variables, it is possible that the stack could be exhausted. If this
occurs, the java run-time system will cause an exception. With the help of recursive method most of algorithm become simpler and clearer
than iterative method. For example, the
QuickSort sorting algorithm is quite difficult to implement in an iterative
way. Fibonacci is simple in Recursive
method.
import java.io.*;
class RecursionFibonacciSeries
{
static
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int
f1,f2,fib,limit;
RecursionFibonacciSeries()
//Constructor method
{
f1=0;
f2=1;
fib=0;
limit=0;
}
void input()throws IOException // input limit of the series
{
{
System.out.print("Enter
the limit : ");
limit=Integer.parseInt(br.readLine());
}
int fibo(int n) //Recursive
function generating the 'nth' term of Fibonacci Series
{
if(n<=1)
return f1;
else if(n==2)
return f2;
else
return (fibo(n-1)+fibo(n-2));
}
void generate_fibseries()
//Function generating all the Fibonacci Series numbers upto 'n' terms
{
System.out.println("The Fibonacci Series is:");
for(int i=1;i<=limit;i++)
{
fib=fibo(i);
System.out.print(fib+" ");
}
}
public static void main(String
args[])throws IOException
{
// Creating object of the class
// Creating object of the class
RecursionFibonacciSeries ob=new RecursionFibonacciSeries();
ob.input();
ob.generate_fibseries();
}
} // main method end
Output:
Enter the limit : 10
The Fibonacci Series is:
0 1 1 2 3 5 8 13 21 34
The Fibonacci Series is:
0 1 1 2 3 5 8 13 21 34