3 Simple Ways to Create Fibonacci Series in Java

The Fibonacci sequence specifies that the current and previous items should be printed together. It all starts with a zero.

If the Fibonacci series maximum is 5, for example, the elements should be displayed as 0, 1, 1, 2, 3. If the number of elements is limited to ten, they should be displayed as 0, 1, 2, 3, 5, 8, 13, 21, 34.

In Java, we have three simple techniques to accomplish Fibonacci Series. These are the ones.

  • Create the Fibonacci Series with the Recursion method
  • Create the Fibonacci Series without the Recursion method
  • Create the Fibonacci Series with Array 

1. Create the Fibonacci Series with the Recursion method

public static void main(String[] args) {
	  FibonacciSeries fs =new FibonacciSeries();
	  System.out.println(fs.fibonacciWithoutRecusion(10));
	  System.out.println(fs.fibonacciWithRecusion(10));
	  System.out.println(Arrays.toString(fs.fibonacciWithoutArray(10)));

	}
	
	private List<Integer> fibonacciWithoutRecusion(int limit) {
		List<Integer> fSeries = new LinkedList<>();
		int currentElement =1,previousElement = 0, temporaryElement = 0;
		fSeries.add(0);
		for(int i=1;i<limit;i++) {    
		  fSeries.add(currentElement);
		  temporaryElement = previousElement;
		  previousElement = currentElement;
		  currentElement = currentElement+temporaryElement;
		 } 
		 return fSeries;
	}

Output :

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

2. Create the Fibonacci Series without the Recursion method

public class FibonacciSeries {        
        List<Integer> fSeries = new LinkedList<>();
	int currentElement =1,previousElement = 0, temporaryElement = 0;
	public static void main(String[] args) {
	  FibonacciSeries fs =new FibonacciSeries();
	  System.out.println(fs.fibonacciWithRecusion(10));
	}
	private List<Integer> fibonacciWithRecusion(int limit) {
		if(fSeries.isEmpty()) fSeries.add(0);
		
		if(--limit>0) {  
		  fSeries.add(currentElement);
		  temporaryElement = previousElement;
		  previousElement = currentElement;
		  currentElement = currentElement+temporaryElement;
		  fibonacciWithRecusion(limit);
		 } 
		 return fSeries;
	}
}

Result :

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

3. Create the Fibonacci Series with Array

       public static void main(String[] args) {
	  FibonacciSeries fs =new FibonacciSeries();
	  System.out.println(Arrays.toString(fs.fibonacciWithoutArray(10)));
	}
	private int[] fibonacciWithoutArray(int limit) {
		int[] fSeriesArray = new int[limit];
		int currElement =1,prevElement = 0, tempElement = 0;
		fSeriesArray[0] = 0;
		for(int i=1;i<limit;i++) {    
		  fSeriesArray[i]=currElement;
		  tempElement = prevElement;
		  prevElement = currElement;
		  currElement = currElement+tempElement;
		 } 
		 return fSeriesArray;
	}

Result :

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

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *