...

/

Solution Review: Generate the Nth Fibonacci Word

Solution Review: Generate the Nth Fibonacci Word

Follow the step-by-step instructions to generate the nth Fibonacci word.

We'll cover the following...

Solution

Press + to interact
#include <stdio.h>
#include <string.h>
void fibWords ( char *, int ) ;
int main( )
{
char strl[1000] = "";
fibWords(strl, 5);
printf ( "%s\n", strl ) ;
return 0 ;
}
void fibWords ( char *strl, int n )
{
// Stores the second last word
char lastbutoneterm[ 50 ] = "A" ;
// Stores the last word
char lastterm[ 50 ] = "B" ;
int i ;
// Handle edge case
if ( n < 0) {
strcpy ( strl, "Empty String") ;
}
// If n == 0 store A
if ( n == 0 ) {
strcpy ( strl, lastbutoneterm ) ;
}
// If n == 0 store B
if ( n == 1 ) {
strcpy ( strl, lastterm ) ;
}
// for loop to generate the nth fibonacci word
for ( i = 2 ; i <= n ; i++ )
{
// Copies last word in strl
strcpy ( strl, lastterm ) ;
// Concatenates second last word with strl
strcat ( strl, lastbutoneterm ) ;
// Copies last word in lastbutoneterm
strcpy ( lastbutoneterm, lastterm );
// Copies current word in last term
strcpy ( lastterm, strl ) ;
}
}

Explanation

The first two words in the Fibonacci word series are A and B, respectively. Each word in Fibonacci is a sum of its previous two words.

Lines 22-24: For n < 0, we will simply store "Empty String" in strl.

Lines 26-32: A Fibonacci word series starts with A and B. ...