• Real-Time-Automation

Fibonacci series in Java

a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.


There are two ways to write the Fibonacci series program in java:

  • Fibonacci Series without using recursion

  • Fibonacci Series using recursion



Fibonacci Series in Java without using recursion


class Fibonacci
{  
 public static void main(String args[])  
 {    
   int k1=0,k2=1,k3,i,count=10;    
   System.out.print(k1+" "+k2);//printing 0 and 1       
   for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already 
   printed   
   {   
    k3=k1+k2;   
    System.out.print(" "+k3);   
    k1=k2;    
    k2=k3;    
   }    
  }
 }

Output:

0 1 1 2 3 5 8 13 21 34

Fibonacci Series using recursion in java

class Fibonacci
{ 
  static int k1=0,k2=1,k3=0;    
  static void printFibonacci(int count){    
  if(count>0)
  {    
    k3 = k1 + k2;   
    k1 = k2;    
    k2 = k3;    
    System.out.print(" "+k3);   
    printFibonacci(count-1);   
  }   
} 
public static void main(String args[])
{    
    int count=10;    
    System.out.print(K1+" "+K2);//printing 0 and 1   
    printFibonacci(count-2);//n-2 because 2 numbers are already   
    printed   
 } 
}  

Output:

0 1 1 2 3 5 8 13 21 34

©2020 by Real Time Selenium WebDriver Automation.