‹ Back to the paper
Question 6(i)
6 marks
Computer ScienceISC 2022 Computer Science - Specimen paper (Semester 2), Paper 1ProgramRecursion
Write the program described below.
A class Fibo has been defined to generate the Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, ………
A class Fibo has been defined to generate the Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, ……. (Fibonacci series are those in which the sum of the previous two terms is equal to the next term).
Some of the members of the class are given below:
Class name: Fibo
Data member/instance variable:
start: integer to store the start value
end: integer to store the end value
Member functions/methods:
Fibo(): default constructor
void read(): to accept the numbers
int fibo(int n): return the nth term of a Fibonacci series using recursive technique
void display(): displays the Fibonacci series from start to end by invoking the function fibo()
Specify the class Fibo, giving details of the Constructor, void read(), int fibo(int), and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.
Answer
Answer
import java.util.*;
class Fibo
{
int start, end;
Fibo()
{
start = 0;
end = 0;
}
void read()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter start: ");
start = sc.nextInt();
System.out.print("Enter end: ");
end = sc.nextInt();
}
int fibo(int n)
{
if (n <= 1)
return n;
return fibo(n - 1) + fibo(n - 2);
}
void display()
{
System.out.println("Fibonacci series from " + start + " to " + end + ":");
int i = 0, t = fibo(0);
while (t <= end)
{
if (t >= start)
System.out.print(t + " ");
i++;
t = fibo(i);
}
System.out.println();
}
public static void main(String[] args)
{
Fibo ob = new Fibo();
ob.read();
ob.display();
}
}fibo(n) is recursive: fibo(0) = 0, fibo(1) = 1, otherwise the sum of the previous two terms. display() prints the terms that lie between start and end. Sample run: start 2, end 50 gives 2 3 5 8 13 21 34.