MOVE ALL X at end

//WHY DOES IT GIVE SEGMENTATION FAULT?
#include
#include
using namespace std;
int f(char* a,int i,int n)
{
if(i==n)
return 0;
if(a[i]==β€˜x’)
{
for( int k=i;k<n;k++)
{
a[k]=a[k+1];
}a[n-1]=β€˜x’;
cout<<a<<endl;
//a[k]=β€˜x’;//a[n]=’\0’;
return(f(a,i,n));
}
return(f(a,i+1,n));
}
int main()
{ char a[1000];
cin>>a;
int n=strlen(a);
int k=f(a,0,n);
cout<<a;
return 0;
}

@POORVI_SAXENA
in if case of your recursive function, you need to call f(a,i,n-1) , because you have placed the x at the last position so you need to touch this index now.

I hope you understood your mistake. Feel free to ask.
If you got it then please mark this doubt as resolved.

1 Like

yes its working now but why does it make any difference?
Because i am shifting till the (n-2)th element everytime and and adding x at last .

Because if you don’t decrease the n then it will keep assigning x to the same last location and it will go into a infinite loop.