print all subsequences

To print all subsequences of a given string in C++, you can use a recursive approach. Here's the code:

#include <iostream>
#include <string>
using namespace std;

void printSubsequences(string str, string current = "", int index = 0)
{
    if (index == str.length())
    {
        cout << current << endl;
        return;
    }

    // Include the current character
    printSubsequences(str, current + str[index], index + 1);

    // Exclude the current character
    printSubsequences(str, current, index + 1);
}

int main()
{
    string str = "abc";
    printSubsequences(str);
    return 0;
}

Let's go through the code and understand each step:

  1. We include the necessary header files: iostream for input/output operations and string for string manipulation.

  2. We define a function printSubsequences that takes three parameters: str (the input string), current (the current subsequence being built), and index (the current index of the string).

  3. Inside the printSubsequences function, we check if the current index is equal to the length of the string. If it is, it means we have reached the end of the string and have formed a subsequence. In this case, we print the current subsequence and return.

  4. If the current index is not equal to the length of the string, we have two options: include the current character in the subsequence or exclude it.

  5. To include the current character, we recursively call the printSubsequences function with the updated current string by appending the current character and incrementing the index by 1.

  6. To exclude the current character, we recursively call the printSubsequences function without changing the current string and incrementing the index by 1.

  7. In the main function, we define a string str with the input value "abc" (you can change it to any other string). We then call the printSubsequences function with str as the argument.

  8. Finally, we return 0 to indicate successful execution of the program.

When you run the code, it will print all the subsequences of the given string "abc" in the console.