fibonacci Series in Java with recursive method

 

Fibonacci Series in Java with recursive method

Recursive method

When a function called by itself directly or indirectly is known as a recursive method or function. The function repeats itself several times and gives outputting the result and the end of each repetition.

Fibonacci Series in Java with recursive method

 A class RecursionFibonacciSeries has been defined to generate the Fibonacci series up to an nth number. Some of the members of the class are given below: 

  • Class Name : RecursionFibonacciSeries
  • Data Members/ instance variables: f1, f2, fib, number;
  • Constructor: RecursionFibonacciSeries ()
  • Member method: input(), fibo(int n), printFibseries()

 In the following java program, input is taken from the input() method.

Then it passes to as int fibo(int n) where the Fibonacci series generate recursively.

After it passes to printFibseries() method for printing of the series.

import java.util.*;

class RecursionFibonacciSeries

{

    // instance variables

    int f1,f2,fib,number;

    int i; // for iteration

    RecursionFibonacciSeries() //Constructor method

    {

        f1=0;

        f2=1;

        fib=0;

        number=0;

    }

    // enter nth value for the series

    void input()

    {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number : ");

        number=sc.nextInt();

    }

    // Recursive method generating the 'nth' term of Fibonacci Series

    int fibo(int n)

    {

        if(n <= 1)

            return f1;

        else if(n == 2)

            return f2;

        else

            // recursion call

            return (fibo(n-1) + fibo(n-2));

    }

 

    void printFibseries() //Function generating all the Fibonacci Series numbers upto 'n' terms

    {

        System.out.println("The Fibonacci Series is:");

        for(i=1; i<=number; i++)

        {

            fib=fibo(i);

            // printing fibonacci series

            System.out.print(fib + "  ");

        }

    }

    // main method

    public static void main(String args[])

    {

        // object creation

        RecursionFibonacciSeries ob=new RecursionFibonacciSeries();

        // calling method

        ob.input(); 

        ob.printFibseries();

  } // end of main method

} // end of class

Output:

Enter the number : 15

The Fibonacci Series is:

0  1  1  2  3  5  8  13  21  34  55  89  144  233  377 

More Java programs 



SHARE THIS
Previous Post
Next Post