Write a Java program that generates an array of Fibonacci numbers. Specification
ID: 3835020 • Letter: W
Question
Write a Java program that generates an array of Fibonacci numbers. Specifications: 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! Prints the Fibonacci numbers in the array 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) 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
import java.util.Scanner;
public class Fibonacci
{
public static void main (String args[])
{
int n = 30;
int f[] = new int[n];
f[0] = 1;
f[1] = 1;
for(int i=2; i<30; i++){
f[i] = f[i-1] + f[i-2];
}
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number in range (1-30");
int num = sc.nextInt();
while(num<1 || num>30){
System.out.print("Enter a number in range (1-30): ");
num = sc.nextInt();
}
System.out.println(num+" fibonacci number is: "+f[num-1]);
sc.close();
}
}
/*
Sample run:
Enter a number in range (1-30): 10
10 fibonacci number is: 55
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.