# Sequence of Fibonacci strings

## ISC Computer Science 2014

### Question 10

A sequence of Fibonacci strings is generated as follows:
S0=”a”, S1=”b”, Sn=S(n-1)S(n-2) where ‘+’ denotes concatenation. Thus the sequence is:
a, b, ba, bab, babba, … n terms.

Design a class FiboString to generate fibonacci strings. Some of the members of the class are given below:

`Class name: FiboString`

Data members/instance variables:

```x  : to store the first string
y  : to store the second string
z  : to store the concatenation of the previous two strings
n  : to store the number of terms```

Member functions/methods:

```FiboString()   : constructor to assign x="a", y="b", z="ba"

void accept()  : to accept the number of terms 'n'

void generate(): to generate and print the fibonacci strings.
The sum of ('+' i.e. concatenation) first two
strings is the third string. Eg. "a" is first
string, "b" is second string then the third string will
be "ba" and fourth will be "bab" and so on.```

Specify the class FiboString, giving details of the constructor(), void accept() and void generate(). Define the main() function to create an object and call the functions accordingly to enable the task.

The Java program for for generating a sequence of strings is as follows:

```import java.util.*;
class FiboString {
private String x, y, z;
private int n;
public FiboString (){
x = "a";
y = "b";
z = "ba";
}
public void accept (){
Scanner sc = new Scanner( System.in );
System.out.print( "Enter number of terms: ");
n = sc.nextInt();
}
public void generate (){
if( n == 1 ){
System.out.print ( x );
}else if( n==2 ){
System.out.print ( x + " " + y );
}else{
System.out.print ( x + " " + y + " ");
for( int i = 1; i <= (n-2) ; i++ ){
z = y + x;
System.out.print ( z + " ");
x=y;
y=z;
}
}
System.out.println ();
}
public static void main ( String args[] ){
FiboString fs = new FiboString ();
fs.accept();
fs.generate();
}
}```

Please note that in the above program on generating a sequence of fibonacci strings, line number 8 is redundant. The assignment (that is z=”ab”) is done just because the question explicitly asked for the assignment in the constructor! The above program on sequence of fibonacci strings with some sample input/output is as follows:

```Enter number of terms: 1
a
Enter number of terms: 2
a b
Enter number of terms: 3
a b ba
Enter number of terms: 4
a b ba bab
Enter number of terms: 5
a b ba bab babba
Enter number of terms: 6
a b ba bab babba babbabab```
Follow me

### Vinay Singh

Computer Teacher at Saint John's Academy
I am a GNU/Linux enthusiast and a computer science teacher by profession based at Allahabad, India. My hobbies include reading (mostly computer related stuff) and photography.
Follow me