How to Display a Fibonacci Series in Java


In this example, we may learn how to create and print Fibonacci Series using Java.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class GetFibonacciSeriesExamples {

	public static void main(String[] args) {

		// Create an array of type long to hold the fibonacci Numbers
		long[] fibonacci = new long[22];

		// Set the first two Numbers to 0 and 1
		fibonacci[0] = 0;
		fibonacci[1] = 1;

		// Start with the third number, which is the sum of the first two.Create
		// Fibonacci Numbers using this rule
		for (int i = 2; i < fibonacci.length; i++) {
			fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
		}

		// Use the toString() method in the Arrays utility class to print the
		// array
		System.out.println(Arrays.toString(fibonacci));

	}

}

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments