Write firstN, a static method that takes an integer parameter n and returns an i
ID: 3621800 • Letter: W
Question
Write firstN, a static method that takes an integer parameter n and returns an integer array of size n, whichcontains the first n Fibonacci numbers. You cannot use the Fibonacci formula we explored in the prior programming
assignment, but in this case they must compute each term in the Fibonacci sequence from the two prior terms (which
are also stored in the array). Recall that the first two terms are both defined to be the number one. You may assume
that the parameter n is positive (n>0), but to be complete you should verify that precondition and throw an
IllegalArgumentException if it is false.
Write a main method to prompt the user for a positive integer n (keep asking until a positive value is entered). Then
create an array which contains the first n Fibonacci numbers by calling firstN(n). Finally, print the n numbers to
the screen.
Example:
This is a sample execution to show you how Fibonacci2.java should behave:
How many Fibonacci numbers would you like to compute? -4
The number must be positive. Try again.
How many Fibonacci numbers would you like to compute? 0
The number must be positive. Try again.
How many Fibonacci numbers would you like to compute? 8
The first 8 Fibonacci numbers are:
1
1
2
3
5
8
13
21
Explanation / Answer
please rate - thanks
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{ Scanner in = new Scanner(System.in);
System.out.print("How many Fibonacci numbers would you like to compute? ");
int n=in.nextInt();
while(n<1)
{System.out.println("The number must be positive. Try again.");
System.out.print("How many Fibonacci numbers would you like to compute? ");
n=in.nextInt();
}
firstN(n);
}
public static void firstN(int n)
{if(n<1 )
throw new IllegalArgumentException("invalid argument");
int[]fib=new int[n];
int i;
fib[0]=1;
fib[1]=1;
for(i=2;i<n;i++)
fib[i]=fib[i-1]+fib[i-2];
System.out.println("The first "+n+" Fibonacci numbers are:");
for(i=0;i<n;i++)
System.out.println(fib[i]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.