In the Fibonacci Series, a number of the series is obtained by adding the last two numbers of the series.
This Java program asks the user to provide input as length of Fibonacci Series.
- Scanner class and its function nextInt() is used to obtain the input, and println() function is used to print on the screen.
- Scanner class is a part of java.util package, so we required to import this package in our Java program.
- We also required to create object of Scanner class to call its functions.
Example:
import java.util.Scanner;
public class FibSeries {
public static void main(String[] args) {
int FibLength;
Scanner sc = new Scanner(System.in); //create object
System.out.print("Please enter length: ");
FibLength = sc.nextInt();
int[] num = new int[FibLength];
//initialized first element to 0
num[0] = 0;
//initialized second element to 1
num[1] = 1;
//New number should be the sum of the last two numbers of the series.
for (int i = 2; i < FibLength; i++) {
num[i] = num[i - 1] + num[i - 2];
}
//Print Fibonacci Series
System.out.println("Fibonacci Series: ");
for (int i = 0; i < FibLength; i++) {
System.out.print(num[i] + " ");
}
}
}
Program Output:
Please enter length: 10 Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
Explanation:
The first two elements are respectively started from 0 1, and the other numbers in the series are generated by adding the last two numbers of the series using looping. These numbers are stored in an array and printed as output.