Write Java program to Print Fibonacci Series


This Java program generates the Fibonacci series of a given length entered by the user. The program uses an array to store the sequence of Fibonacci numbers, with each number in the sequence equal to the sum of the two preceding numbers.

  • The program starts by creating a Scanner object to read input from the user. It then prompts the user to enter the length of the Fibonacci series they want to generate, which is stored in the integer variable n.
  • The program then creates an integer array num of length n to store the Fibonacci series. The first two elements of the array (num[0] and num[1]) are initialized to 0 and 1, respectively, since these are the first two numbers in the Fibonacci sequence.
  • The program then uses a for loop to fill the rest of the array with the remaining numbers in the Fibonacci sequence. Each number in the sequence is equal to the sum of the two preceding numbers, which are stored in num[i - 1] and num[i - 2] , respectively. The sum of these two numbers is then assigned to num[i].
  • Finally, the program uses another for loop to print out the entire Fibonacci series, one number at a time, using System.out.print().

Overall, this program is a straightforward way to generate the Fibonacci series of a given length in Java using an array. However, it is worth noting that the Fibonacci sequence grows very quickly, and the numbers in the series can become very large for large values of n. In some cases, it may be necessary to use a more efficient algorithm to compute the Fibonacci sequence, such as memoization or matrix exponentiation.

Source Code

import java.util.Scanner;
public class Fabonacci_Series
{
	public static void main(String[] args)
	{
		int n;
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the Length of Fibonacci Series : ");
		n = input.nextInt();
 
		int[] num = new int[n];
		num[0] = 0;
		num[1] = 1;
 
		for (int i = 2; i < n; i++)
		{
			num[i] = num[i - 1] + num[i - 2];//sum of last two numbers
		}
 
		System.out.print("Fibonacci Series : ");
		for (int i = 0; i < n; i++)
		{
			System.out.print(num[i] + " ");
		}
	}
}

Output

Enter the Length of Fibonacci Series : 8
Fibonacci Series : 0 1 1 2 3 5 8 13

Example Programs