A string to rotate it by n characters

i tried to solve this question using swapping technique but got wrong output.
int main()
{

char s[30]="hello";
int k;
char ch,x;
cin>>k;
int l=strlen(s);
for(int i=0;i<=l/2;i++)
{

    ch=s[i];
    s[i]=s[i+k];
    s[i+k]=ch;

}

for(int i=(l/2)+1;i<l;i++)
{
     x=s[i];
     s[i]=s[i-k-1];
    s[i-k-1]=x;

}

cout<<s;

}

Hello @Adi,

From next time, please share your code using Online Coding Blocks IDE.
Steps:

  1. Paste your code at https://ide.codingblocks.com/
  2. Save it there.
  3. Share the URL generated.

The way you have to send it, introduces syntax errors to it.

Now, coming back to your code:
Can you explain the logic you are trying to implement?
It would not work.

  1. The first loop will access the index>length(string) for k>len/2
  2. The second loop will shift the elements by k-1 positions to left.

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.