Write a Java program that generates an array of Fibonacci numbers. Specification
ID: 3897523 • Letter: W
Question
Write a Java program that generates an array of Fibonacci numbers. Specifications: The program . Fills a one-dimensional array with the first 30 Fibonacci numbers using a calculation to generate the numbers. Note: The first two Fibonacci numbers 0 and 1 should be generated explicitly as in long[] series new long[limit] //create first 2 series elements series[O] 0; series[1]1; . But, it is not permissible to fill the array explicitly with the Fibonacci series' after the first two elements (0 and 1). From that point on the numbers must be calculated.Explanation / Answer
import java.util.*;
class Fibonacci {
// Calculating the Fibonacci values
public static void calculate(long[] arr) {
int a=0,b=1,c,i;
for(i=2;i<30;i++) {
c=a+b;
a=b;
b=c;
arr[i] = c;
}
}
public static void main(String[] args) {
long[] series = new long[30];
// Implicit declaration
series[0] = 0;
series[1] = 1;
// Explicit calculation
calculate(series);
int i=0;
// Displaying all the values in the array
System.out.println("The first 30 numbers of Fibonacci:");
for(;i<30;i++)
System.out.print(series[i] + " ");
int inp = 0;
Scanner sc = new Scanner(System.in);
// Input the user value and check whether it's in the range of 1-30
do{
System.out.print(" Which of the number in this series you want to see: ");
inp = sc.nextInt();
if(inp>0 && inp<31)
break;
else
System.out.print("Must be in the range of 1 to 30");
} while(true);
// Array index starts at zero, thus input - 1 is calculated
System.out.println("The " + inp + "th Fibonacci number is " + series[inp-1]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.