Java Program demonstrating the Fibonacci Sequence

The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

in which the next number is found by adding up the two numbers before it.

A Formula can be generated for this like

Xn= Xn-1 + Xn-2

where:

  • xn is term number “n”
  • xn-1 is the previous term (n-1)
  • xn-2 is the term before that (n-2)

Here is the Java Program creating a Fibonacci Sequence till 25 digits. An array is used to store the Fibonacci Sequence using  a for loop.


public class FibonacciSeriesDemo {

	public static void main(String[] args) {

	//Setting the number of elements to generate in the fibonacci series

	int limit = 25;

	long[] fibonacciSeries = new long[limit];

	// Initialize the First two elements of the Fibonacci Series
	fibonacciSeries[0] = 0;

	fibonacciSeries[1] = 1;

	//Create the Fibonacci series and store it in an array

	for(int i=2; i < limit; i++){
		fibonacciSeries[i] = fibonacciSeries[i-1] + fibonacciSeries[i-2];
	}

	//print the Fibonacci series numbers
	System.out.println("Fibonacci Series upto " + limit);
        System.out.println();
	for(int i=0; i< limit; i++){

		System.out.print(fibonacciSeries[i] + " ");
	}

}//main

}

Snapshot of the output

JavaFibonacciSeriesDemoProgramOutput

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s