My code isnt working

I’m getting the wrong output.
Here’s the code: https://ide.codingblocks.com/s/646485

Hey @mitrapranav0027_5d705c8b616e0add your logic is correct there are some minor mistakes

  1. the j variable you are using has no use and j will become n after 1st while loop
    and in 2nd while loop swaps will occur n times as j=n and while(j) will run for n times which is not required as recursion will do that for you.

  2. no need to change last position as x " a[x+1]=‘x’; " because swaps will do that for you.

  3. your base condition is wrong as according to your base condition xToEnd(a,i,n); this call will lead to infinite loop and time limit will exceed instead you should make it if(i>=n) {
    return;
    }

refer to corrected code for more clearance

#include
#include
using namespace std;
void xToEnd(char *a,int i,int n) {
// Base Case
if(i>=n) {
return;
}

// Recursive case
if(a[i]=='x') {

	int x=i;
	while(a[x]!='\0' && a[x+1]!='\0'){
		a[x]=a[x+1];
		x++;
	}
	xToEnd(a,i,n-1);
}
else
	xToEnd(a,i+1,n);

}
int main() {
char a[1000];
cin>>a;
int len = strlen(a)-1;
xToEnd(a,0,len);
cout<<a;

return 0;

}

Happy coding :slight_smile:

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.

Thank you for such a comprehensive reply. Although, the code you shared was not working correctly so I had to add “a[x]=‘x’;” after the while loop so as to add x’s at the end. Also I have a question regarding the 1st point: 1. How is j n after ever loop. won’t it be n-i since its value is starting from i in every recursion?

@mitrapranav0027_5d705c8b616e0add j will not be n-i because it is initialized to i+1 before the while loop and till it reaches end of string it will keep incrementing till n.