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:
We include the necessary header files:
iostream
for input/output operations andstring
for string manipulation.We define a function
printSubsequences
that takes three parameters:str
(the input string),current
(the current subsequence being built), andindex
(the current index of the string).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.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.
To include the current character, we recursively call the
printSubsequences
function with the updatedcurrent
string by appending the current character and incrementing theindex
by 1.To exclude the current character, we recursively call the
printSubsequences
function without changing thecurrent
string and incrementing theindex
by 1.In the
main
function, we define a stringstr
with the input value "abc" (you can change it to any other string). We then call theprintSubsequences
function withstr
as the argument.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.