Recursion program in Java

Recursion program in Java

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.
Specify the class Recursion giving details of the constructorint fibo() , void generate_fibseries(). You may assume other functions are written for you and you need not write the main function.

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.

class RecursionFibonacciSeries
    static BufferedReader br=new BufferedReader(new                  InputStreamReader(;
    int f1,f2,fib,limit;
RecursionFibonacciSeries() //Constructor method
void input()throws IOException        // input limit of the series
     System.out.print("Enter the limit : ");
int fibo(int n) //Recursive function generating the 'nth' term of Fibonacci Series
    return f1;
    else if(n==2)
    return f2;
    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++)
            System.out.print(fib+"  ");
public static void main(String args[])throws IOException
   // Creating object of the class
   RecursionFibonacciSeries ob=new RecursionFibonacciSeries();
} // main method end
Enter the limit : 10
The Fibonacci Series is:
0 1 1 2 3 5 8 13 21 34 

You may also interestd in

Java method or function

Previous Post
Next Post