Search⌘ K
AI Features

Solution Review: Generate the Nth Fibonacci Word

Explore how to generate the nth Fibonacci word by concatenating previous terms in the series. Understand handling base cases and constructing the sequence using string operations in C, enhancing your skills in string manipulation and algorithm implementation.

We'll cover the following...

Solution

C
#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 ) ;
}
}
...