Print the first N terms of the Sturmian sequence

Updated

Sturmian sequence is the sequence formed by substituting 0 with 01 and 1 with 0 where the first term starts with 0.

0 -> 01

1 -> 0,

giving

0->01->010->01001->01001010->…,

Find the N terms of Sturmian Sequence

Given an integer N, the task is to print the first N terms of the Sturmian sequence.

Examples :

Input : N = 3
Output : 0, 01, 010

Input : N = 5
Output : 0, 01, 010, 01001, 01001010

Approach :

  1. Initialise a string s = “” and Run loop n times and in each iteration run another loop of string length s to convert 0 to “01” and 1 to “0” and store in another string s1.
  2. After completion of each iteration, assign string s=s1, and insert string s in a vector, and initialize s1 = “”
  3. After above loops are completed, print the vector

Implementation :

// C++ implementation of the

// above approach



#include <bits/stdc++.h>

using namespace std;



// Function to print the first N terms

// of the Sturmian Sequence

void SturmianSequence(int n)

{

   // vector to strong Sturmian Sequence

   vector<string> v;

       

   string s = "0";

   v.push_back(s);

   

   string s1 = "";

 for (int x = 1; x <= n; x++)

 {

   for (int y = 0; y < s.length(); y++)

   {

     if (s[y] == '0')  // 0 01

       s1 += "01";

     else

       s1 += "0";      

   }

   v.push_back(s);

   // Assign s1 string in s string

   s = s1;

   s1 = "";

 }  

 

   // printing  Sturmian Sequence

   for(int i = 1; i <= n; i++)

   cout << v[i] << ", ";

}



// Driver code

int main()

{

   int n = 4;



   SturmianSequence(n);



   return 0;

}

Output : 0, 01, 010, 01001,

Comment
Next tutorial
Mithlesh Upadhyay Published 26 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials