on Leave a Comment

Java Program to Print Fibonacci Series

In Fibonacci series, next term is sum of previous two terms. Fibonacci series is followed by 0 and 1.

Example of Fibonacci series is 0  1  1  2  3  5  8  13  21  34.....

Java program to print Fibonacci series without recursion


public class FibonacciSeries
{
	public static void main(String[] args)
	{
	    int a1 = 0, a2 = 1, n = 10;
	    System.out.println("Fibonacci series of first "+n+"th terms:");
	    for(int i = 1; i<=10; i++)
	    {
		System.out.print(a1 + "  ");
                int sum = a1 + a2;
                a1 = a2;
                a2 = sum;
	     }
	}
}

Output:


Fibonacci series of first 10th terms:
0  1  1  2  3  5  8  13  21  34


Java program to print Fibonacci series using recursion


public class FibonacciSeries
{
	static int a1 = 0, a2 = 1, n = 10, sum = 0;
        static void showFibonacci(int count)
	{    
            if(count>0)
	    {    
               sum = a1 + a2;    
               a1 = a2;    
               a2 = sum;    
               System.out.print(" "+sum);   
               showFibonacci(count-1);    
            }    
        } 
	public static void main(String[] args)
	{
	      System.out.println("Fibonacci series of first "+n+"th terms:");
	      System.out.print(a1+" "+a2);
	      showFibonacci(n-2);
	}
}

Output:


Fibonacci series of first 10th terms:
0  1  1  2  3  5  8  13  21  34

0 comments:

Post a Comment