Fibonacci series using recursion in JAVA programming


import java.util.Scanner;

public class FibonacciRecursion {

    public static void main(String[] args) {
        Scanner myScanner=new Scanner(System.in);
        //---------Input-------------
        System.out.print("Enter how many terms you want : ");
        int n=myScanner.nextInt();
      
        for (int i = 1; i <=n; i++) {
            System.out.print(fib(i)+"\t");
        }
    }
  
    //--------------Fibonacci method----------------
    static int fib(int n)
    {
        int f;
        if (n==1) {
            f=0;
        }else if(n==2){
            f=1;
        }
        else{
            f=fib(n-1)+fib(n-2);
        }
        return f;
    }
}
//Enter how many terms you want : 10
//0    1    1    2    3    5    8    13    21    34   

Share this

Related Posts

Previous
Next Post »