Page 412 - Cs_withBlue_J_C11_Flipbook
P. 412
Some More Programs #Interdisciplinary
#Creativity & Innovativeness
Program 1 A class called Fibo is defined which will print the first ‘n’ terms of a Fibonacci series. Fibonacci
series is a series in which any term is equal to the sum of its previous two terms. The first two
terms are 0 and 1. The series is 0, 1, 1, 2, 3, 5, 8, 13, ... up to n terms. The class description is
given below:
Class name : Fibo
Data Members
int n : Number of terms
Member Methods
Fibo() : Constructor to initialise n to 0
void getnum(int nn) : Initialises n to nn
int generate(int x) : Returns the xth term of the series
void print() : Prints the first ‘n’ terms of a Fibonacci series
static void main() : Creates objects and calls the other methods to do the same
1 class Fibo
2 {
3 int n;
4 Fibo()//constructor
5 {
6 n=0;
7 }
8 void getnum(int nn)//accept number
9 {
10 n=nn;
11 }
12 int generate(int x)
13 {
14 if(x<=1) // base case
15 return x;
16 else
17 return generate(x-1)+ generate(x-2); // recursive case
18 }
19 void print()
20 {
21 System.out.println("First "+ n +" terms of a Fibonacci series are");
22 for(int i=1;i<=n;i++)
410410 Touchpad Computer Science-XI

