In: Computer Science
Create a program “Fib.java” and a method called “double[] getFib)” that creates an array with a length of 15 that contains the first 15 numbers in the Fibonacci sequence and returns it. Set the first element to 0 and the second element to 1, then use a for loop to fill out the rest of the array.
// formula for fibonacci Fn = F(n-1) + F(n-2) n>=2 F[0]=0.0
F[1]=1.0
class Fib{
//function for calculating 15 fibonacci numbers
public double[] getFib(){
int
num1=0,num2=1,num3,i,size=15;
double[] fibArray = new
double[15]; //double type array for stroing fibonacci
values
fibArray[0]=num1;
//first fibonacci number
fibArray[1]=num2;
//second fibonacci number
//loop for calculating third
fibonacci number to 15th fibonacci numbers
for(i=2;i<size;i++){
num3=num1+num2; //next fibonacci number calculated by
sum of previous two fibonacci values
fibArray[i]=num3; //storing next fibonacci value in to
array
num1=num2;
num2=num3;
}
return fibArray;
//returning array
}
public static void main(String args[]){
Fib obj =new Fib();
//object creation
double[] res =
obj.getFib(); //stroing function return array
//displaying first 15 fibonacci
numbers
for(int i=0;i<15;i++){
System.out.println((i+1)+" fibnocci number fib["+i+"] =
"+res[i]);
}
}
}