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 wordchar lastbutoneterm[ 50 ] = "A" ;// Stores the last wordchar lastterm[ 50 ] = "B" ;int i ;// Handle edge caseif ( n < 0) {strcpy ( strl, "Empty String") ;}// If n == 0 store Aif ( n == 0 ) {strcpy ( strl, lastbutoneterm ) ;}// If n == 0 store Bif ( n == 1 ) {strcpy ( strl, lastterm ) ;}// for loop to generate the nth fibonacci wordfor ( i = 2 ; i <= n ; i++ ){// Copies last word in strlstrcpy ( strl, lastterm ) ;// Concatenates second last word with strlstrcat ( strl, lastbutoneterm ) ;// Copies last word in lastbutonetermstrcpy ( lastbutoneterm, lastterm );// Copies current word in last termstrcpy ( 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
. ...