Fibonacci Word

Like Fibonacci numbers, a Fibonacci word. is a specific sequence of binary digits (or symbols from any two-letter alphabet). The Fibonacci word is formed by repeated concatenation in the same way that the Fibonacci numbers are formed by repeated addition. But unlike the fibonacci number, Fibonacci word has its first two terms different from each other.

In Fibonacci word,
  S(0) = 0, 
  S(1) = 01, 
  S(2) = 010,
  S(3) = 01001
where S(n) = S(n-1) + S(n-2) and + 
represents the concatenation of 

The task is to find nth Fibonacci word for a given number n.


Input : n = 4
Output : S(4) = 01001010

Input : n = 2
Output : S(2) = 010

Just like in program of Fibonacci number, we use the iterative concept of finding nth Fibonacci number here for finding nth Fibonacci word we can use the iterative concept. So for finding n-th Fibonacci word we will take two string Sn and Sn_1 which represent S(n) and S(n-1) respectively and on each iteration we will update tmp = Sn, Sn = Sn + Sn_1 and Sn_1 = tmp in this way we can find nth fibonacci word.


// program for nth Fibonacci word
using namespace std;

// Returns n-th Fibonacci word
string fibWord(int n)
    string Sn_1 = "0";
    string Sn = "01";
    string tmp;
    for (int i=2; i<=n; i++)
        tmp = Sn;
        Sn += Sn_1;
        Sn_1 = tmp;

    return Sn;

// driver program
int main()
    int n = 6;
    cout << fibWord(n);
    return 0;


// Java program for nth Fibonacci word
import java.util.*;

class Eulerian
    // Returns n-th Fibonacci word
    public static String fibWord(int n)
        String Sn_1 = "0";
        String Sn = "01";
        String tmp;
        for (int i=2; i<=n; i++)
            tmp = Sn;
            Sn += Sn_1;
            Sn_1 = tmp;

        return Sn;
    // driver code
    public static void main(String[] args)
        int n = 6;

// This code is contributed by rishabh_jain


# Python3 program for nth Fibonacci word

# Returns n-th Fibonacci word
def fibWord(n):
    Sn_1 = "0"
    Sn = "01"
    tmp = ""
    for i in range(2, n + 1):
        tmp = Sn
        Sn += Sn_1
        Sn_1 = tmp
    return Sn

# driver program
n = 6
print (fibWord(n))

# This code is contributed by Sachin Bisht



Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Please write to us at to report any issue with the above content.

Recommended Posts:

0 Average Difficulty : 0/5.0
No votes yet.