Fibonacci series using recursion - Coder's point

Saturday, March 16, 2019

Fibonacci series using recursion

 import java.util.*;  
 class FibonacciSeries{   
   int n1=0,n2=1,n3=0;    
   void printFibonacci(int count)  
   {    
     if(count>0){    
       n3 = n1 + n2;    
       n1 = n2;    
       n2 = n3;    
       System.out.print(" "+n3);    
       printFibonacci(count-1);    
     }    
   }    
   public static void main(String args[]){    
     FibonacciSeries ob = new FibonacciSeries();  
     Scanner in =new Scanner(System.in);  
     System.out.println("Enter the limit");  
     int count=in.nextInt();  
     int n1=0,n2=1,n3=0;   
     System.out.print(n1+" "+n2);//printing 0 and 1    
     ob.printFibonacci(count-2);//n-2 because 2 numbers are already printed    
   }   
 }   
OUTPUT
Enter the limit
7
0 1 1 2 3 5 8

No comments:

Post a Comment