Learnitweb

Write Java program to print Fibonacci series

Fibonacci series is a series of numbers in which each number(Fibonnaci number) is the sum of the two preceding numbers, starting from 0 and 1. For example:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

There are two ways to generate Fibonacci series in Java:

  • Without using recursion
  • Using recursion

Fibonacci series without recursion

public class FibonacciSeriesWithoutRecursion {
	
	public static void printFibonacciSeries(int count){
		int firstNumber = 0;
		int secondNumber = 1;
		int i;
		//print first two numbers
		System.out.print(firstNumber + ", " + secondNumber);
		// loop starts from 2 because first two numbers(0 and 1) are already printed
		for (i = 2; i < count; ++i)
		{
			int nextNumber = firstNumber + secondNumber;
			System.out.print(", " + nextNumber);
			firstNumber = secondNumber;
			secondNumber = nextNumber;
		}
	}
	
	public static void main(String args[]) {
		int count = 10;
		printFibonacciSeries(count);
	}
}

Output

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Fibonacci series using recursion

public class FibonacciSeriesUsingRecursion {
	static int firstNumber = 0;
	static int secondNumber = 1;
	static int nextNumber;
	
	public static void printFibonnaciSeries(int count){
		
		if(count > 0){    
	         nextNumber = firstNumber + secondNumber;    
	         firstNumber = secondNumber;    
	         secondNumber = nextNumber;    
	         System.out.print(", " + nextNumber);   
	         printFibonnaciSeries(count-1);    
	     }   
	}
	
	public static void main(String args[]) {
		int count = 10;
		System.out.print(firstNumber + ", " + secondNumber);
		printFibonnaciSeries(count - 2);
	}
}

Output

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Fibonacci series up to a number

public class FibonacciSeriesUptoANumber {
	static int firstNumber = 0;
	static int secondNumber = 1;
	static int nextNumber = 0;
	public static void printFibonnaciSeries(int limit){
		
		while(firstNumber <= limit)
		{
			System.out.print(firstNumber + " ");
			nextNumber = firstNumber + secondNumber;
			firstNumber = secondNumber;
			secondNumber = nextNumber;
		}
	}

    public static void main(String[] args) {
    	int limit = 10;
		printFibonnaciSeries(limit);
    }

}

Output

0 1 1 2 3 5 8