So, my question is to write a C++ program to print all the substrings of a given string using recursion. It was in a free youtube course in which the teacher just tells questions and their answer without a detailed explanation. So, I copied that code and executed it and it was working but I wanted to check how the stack is being managed so I made the stack and found an issue.
You can check the details of the question like the question statement, c++ code, output, explanation, stack, etc. in this image: https://photos.app.goo.gl/yQuiSFwfVB4GnDGg9
I am also attaching the code here:
#include<iostream>
using namespace std;
void sub( string s, string ans="")
{
if(s.length()==0)
{
cout<<ans<<endl;
return;
}
char ch = s[0];
string ros = s.substr(1); //ros- Rest of the string
sub(ros,ans);
sub(ros,ans+ch);
}
int main()
{
sub("ABC","");
return 0;
}
And the output of the code is:
C
B
BC
A
AC
AB
ABC
EDIT: It is hard to tell the issue in words but I will try. The stack keeps calling the function till it reaches the base condition and returns. So, according to the code, every function call will call the function twice annd this will keep happening till it reaches the base condition. So, it looks similar to a binary tree (as shown in the image). Now, the issue is that the last 2 nodes of that tree are not being executed by the compiler.
Let me try to elaborate a bit on it. I will try to tell how the function executes and creates the stack but I will be mainly focusing on the 2nd call which is sub(ros,ans+ch) and ignore the first call which is sub(ros,ans) because the problem is that the second last call of sub(ros,ans+ch) is not being executed.
So, the main function will call sub("ABC","") which will call 2 functions sub("BC","") and sub("BC","A"). Lets ignore the sub("BC","").
The sub("BC","A") will call 2 functions that are sub("C","A") and sub("BC","AB"). Lets ignore the first call again.
sub("BC","AB") will call sub("C","AB") and sub("C","ABB"). Ignoring the first call again means:
sub("C","ABB") will call sub("","ABB") and sub("","ABBC").
These 2 calls will reach the base case and should print ABB and ABBC at the end of the program but it is not happening.
According to the stack, the output is correct but it should have another 2 lines of output containing strings ABB and ABBC which is not happening. I have checked the stack execution multiple times since last 24 hours and I don't see any problem with that. Any help is appreciated, thanks.