Write a Java program that generates an array of Fibonacci numbers. Add comments
ID: 3771462 • Letter: W
Question
Write a Java program that generates an array of Fibonacci numbers. Add comments to the program.
Specifications:
1. Fills a one-dimensional array with the first 30 Fibonacci numbers using a calculation to generate the numbers. Note: it is not permissible to initialize the array explicitly with the Fibonacci series’ first 30 numbers!
2. Prints the Fibonacci numbers in the array
3. Prompts the user to input an (integer) number between 1 and 30 (inclusive) and prints in response to the user entry: The nth Fibonacci number is X, where n is the number input by the user and X is the Fibonacci number in the nth position. (Remember that array indexes for the elements of the array start at 0)
4. Checks that the user has not input a number lower than 1 or higher than 30
You can check if you have the right numbers here:
http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html
Explanation / Answer
Output:
Enter any number : 10
Fibonacci Series upto 10
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
import java.io.*;
import Java.until.*;
public class FibonacciSeries{
public static void main(String[] args) {
//number of elements to generate in a series
System.out.println(" Enter any number below 30 ");//User enter the number
Scanner s= new Scanner(System.in); // it is used to read the input
int f=s.nextInt(); // integer conversion
long[] series = new long[f];
//create first 2 series elements
series[0] = 0;
series[1] = 1;
//create the Fibonacci series and store it in an array
for(int i=2; i <=f; i++){
series[i] = series[i-1] + series[i-2];
}
//print the Fibonacci series numbers
System.out.println("Fibonacci Series upto " + f);
for(int i=0; i<=f; i++){
System.out.print(series[i] + " ");
}
} // end of class
} // end of main method
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.