Fibonnaci series Recursion Program in Java : Code with Example

This series was first introduced into the world by well known mathematician  Leonardo Fibonnaci .
This series has special characteristic ,which differs from the rest .Here we presents a recursive solution
for the fibonnaci series .

Fibonacci Series is as follow :

0,1,1,2,3,5,8,13,21.34,55,89,144,233,377,610 .........

Read Also :  Armstrong Number Java swing code with Example


Speciality of Fibonnaci  :

> The number series contains the whole number only

>  The next number in the series is the sum of previous two numbers .

> Series starts from 0 and 1  .(the first whole numbers )

>The higher up in the sequence ,the more closely the ratio of two consecutive Fibonnaci numbers will approach the golden ratio  (approximately 1 : 1.618 or 0.618 : 1)


Pseudo Code :


*  User is prompt to set the number of terms to display in the fibonacci series 

*  User sets the number of terms in the series .

* if n=1 
          then display 1 
  else if n=2 
          then display 1
  else 
          using recursion, calculate and  display all the  terms


Read Also :   Prime number Verification Java swing code with Example


Demo


fibonnaci series





































Please find the code below :



import java.io.*;
import java.lang.*;
class Demo {
    int fib(int n) {
        if(n==1)
        return (1);
        else if(n==2)
        return (1);
        else
        return (fib(n-1)+fib(n-2));
    }
}
class RecFibDemo {
    public static void main(String args[])throws IOException {
        InputStreamReader obj=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(obj);
        System.out.println("enter last number");
        int n=Integer.parseInt(br.readLine());
        Demo ob=new Demo();
        System.out.println("fibonacci series is as follows");
        int res=0;
        for(int i=1;i<=n;i++) {
            res=ob.fib(i);
            System.out.println(" "+res);
        }
        System.out.println();
        System.out.println(n+"th value of the series is "+res);
    }
}

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry