Please write a function named Fibonacci that takes an int indicating the length
ID: 638262 • Letter: P
Question
Please write a function named Fibonacci that takes an int indicating
the length of the series. The function prototype could look like
void Fibonacci( int length );
Use a local array of size 20 to store the sequence of numbers and
then print the sequence in reverse order (largest number first);
display 6 numbers per line and use 5 positions for each number;
if the user asked for 20 numbers, your program should display
4181 2584 1597 987 610 377
233 144 89 55 34 21
13 8 5 3 2 1
1 0
Your program should make sure that length the series (i.e., the
int being passed to the Fibonacci function) is >= 2 and <= 20;
otherwise your program should display a message that length is out of
bounds and terminate the execution.
This assignment is due on the BlackBoard by midnight one week from
the day it was assigned. Submit only the lab02.cpp file.
No late assignments.
Please
- use braces around any block
- use blocks as we did in our class examples
- indent your code as we have used indentations in our examples
- comment your code; do not over comment your code
Penalties:
o -2 for each missing block
o -2 for each missing indentation
o no credit if your cpp file does not compile or does not run
o some partial credit if your program crashes with different
input values depending on the problem
Extra credit:
- one extra point if your program correctly allocates and deallocates
a dynamic array for length elements instead of using a fixed size
array of size 20 to hold the numbers in the Fibonacci series.
end of lab 02.
Explanation / Answer
public class Fibonacci {
private int[] a;
private int fib(int i) {
assert (i>=0);
if (a[i]==0) {
if (i==0 || i==1) {
a[i] = 1;
} else {
a[i] = fib(i - 2) + fib(i - 1);
}
}
return a[i];
}
public Fibonacci(int numberTerms) {
if (numberTerms<2) throw new IllegalArgumentException("expect at least 2 terms for a Fibonacci sequence");
a = new int[numberTerms];
}
int count=0;
public void print() {
print(a.length - 1);
}
public void print(int i) {
if (i > 0) {
if(count==5){
System.out.println(" ");
System.out.println(fib(i - 1));
print(i - 1);
count=0;
}
else{
System.out.println(fib(i - 1));
print(i - 1);
}
}
}
public static void main(String[] args) {
Fibonacci f = new Fibonacci(7);
f.print();
}
}