Replace all pi(recursion)

#include
#include
using namespace std;
string replace_pi(string s,int n,int i){
if(n<=1){
return s;
}
string res=replace_pi(s,n-1,i+1);
if(s[i-1]==‘p’&&s[i]==‘i’)
{
res=res.substr(0,i)+“3.14”+res.substr(i+2);
}
else
return res;
}
int main(){
int t;
cin>>t;
for(int i=0;i<t;i++){
string s;
getline(cin,s);
int n=s.length();
cout<<replace_pi(s,n,0);
}
}
whats wrong in this code?

Hi @tishya_goyal, there are some errors in your code like

  1. string res=replace_pi(s,n-1,i+1); here you are passing string as a whole but actually it should be replace_pi(s.substr(i+1,n),n-1,i+1) ,
  2. you have to consider base cases like i=0 as in case of i=0 ,s[i-1] will compute to s[-1] which is an invalid index and lead to runtime error

here check this simple code : - https://ide.codingblocks.com/s/213799
i have discussed the code along with the logic
In case of any doubt feel free to ask :slight_smile:
If you got the answer then mark your doubt as resolved

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.