Write a Java program that generates an array of Fibonacci numbers. Specification
ID: 3772358 • 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
Explanation / Answer
Program:
Sample output:
Code to copy:
import java.util.Scanner;
public class FibArray
{
public static void main(String arg[])
{
Scanner input=new Scanner(System.in);
int n,i=0;
int Fib[]=new int[30];
//Fill array Fib with first 30 fibonacci numbers
while(i<30)
{
if(i<2)
{
Fib[i]=i;
}
else
{
Fib[i]=Fib[i-1]+Fib[i-2];
}
i++;
}
System.out.println("Enter a number between 1 and 30: ");
n=input.nextInt();
//validate user input
while(n<1 || n>30)
{
System.out.println("Sorry ! Enter a number between 1 and 30: ");
n=input.nextInt();
}
//print nth fibonacci number
System.out.println(n+" th Fibonacci number is "+Fib[n-1]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.