Search

Fibonacci series in Java || Java Programs

In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1.


Fibonacci Series in Java without using recursion


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

Output -

0 1 1 2 3 5 8 13 21 34

Fibonacci Series using recursion in java



class FibonacciExample2{  
 static int n1=0,n2=1,n3=0;    
 static 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[]){    
 int count=10;    
  System.out.print(n1+" "+n2);//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




Related Posts

See All

How to Print Pattern in Java || Java Programs

Java pattern program enhances the coding skill, logic, and looping concepts. It is mostly asked in Java interview to check the logic and thinking of the programmer. We can print a Java pattern program

How to Generate Random Number in Java || Java Programs

In real world projects, we often required to generate random numbers while we develop applications. Many applications have the feature to generate numbers randomly, such as to verify the user many app

Armstrong Number in Java || Java Programs

Armstrong Number in Java: A positive number is called armstrong number if it is equal to the sum of cubes of its digits for example 0, 1, 153, 370, 371, 407 etc. Let's try to understand why 153 is an

  • Facebook
  • Instagram
  • LinkedIn
  • 1024px-Telegram_logo.svg
  • download
  • YouTube
  • Google Play