A class FibList is designed to extract the terms of the Fibonacci series from a set of numbers.
A Fibonacci series starts with terms 0 and 1. All the other terms in this series are generated by adding the previous two terms.
A Fibonacci series with 8 terms will be 0, 1, 1, 2, 3, 5, 8, 13.
Example:
Input array = {1, 4, 9, 3, 10, 13, 7} then,
Output array = {1, 3, 13}
The details of the members of the class are given below:
Class name: FibList
Data members/instance variables:
list[]: array to hold positive integers
size: to store the size of array
Methods/Member functions:
FibList(int s): constructor to assign size = s
void read(): to accept the elements of the array
boolean checkFib(int n): to check and return true if n is a Fibonacci term otherwise return false.
FibList genFib(FibList fbl): to return a new object containing only Fibonacci terms from the object fbl by invoking the method checkFib() as per the given instructions
void display(): to display the elements of the original array and the array holding the Fibonacci terms.
Specify the class FibList giving details of the constructor, void read(), boolean checkFib(int), FibList genFib(FibList) and void display(). Define the main() function to create objects and call the functions accordingly to enable the task.
import java.util.Scanner;
class FibList{
int list[];
int size;
public FibList(int s){
size = s;
list = new int[size];
}
public void read(){
Scanner in = new Scanner(System.in);
System.out.println("Enter " + size + " elements:");
for(int i = 0; i < size; i++)
list[i] = in.nextInt();
}
public boolean checkFib(int n){
if(n == 0 || n == 1)
return true;
int a = 0;
int b = 1;
int c;
do{
c = a + b;
if(c == n)
return true;
a = b;
b = c;
}while(c < n);
return false;
}
public FibList genFib(FibList fbl){
int count = 0;
for(int i = 0; i < size; i++){
if(checkFib(list[i]))
count++;
}
if(count == 0){
System.out.println("NO FIBONACCI TERMS");
System.exit(0);
}
FibList obj = new FibList(count);
int index = 0;
for(int i = 0; i < size; i++){
if(checkFib(list[i]))
obj.list[index++] = list[i];
}
return obj;
}
public void display(){
for(int i = 0; i < size; i++)
System.out.print(list[i] + " ");
System.out.println();
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Number of elements: ");
int count = in.nextInt();
FibList obj1 = new FibList(count);
obj1.read();
FibList obj2 = obj1.genFib(obj1);
System.out.print("Input array = ");
obj1.display();
System.out.print("Output array = ");
obj2.display();
}
}