Thursday, 17 January 2019

C Program to reverse middle K characters

The program must accept a string S and an integer K as the input. The program must reverse the middle K characters in S. Then the program must print the modified string as the output.
Note:  The length of S and the integer K are always either odd or even.

Boundary Condition(s):

1 <= Length of S <= 100
1 <= K <= Length of S

Input Format:

The first line contains the string S.
The second line contains the integer K.

Output Format:
The first line contains the modified string.

Example
Input:
acknowledgement
7

Output:
acknegdelwoment

Program
#include<stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
   int K,cnt=0,i=0,j,a,l;
   char S[100],tmp[100];
   scanf("%s%d",S,&K);
   a=strlen(S);
   if ((a%2==0 && K%2==0) || (a%2!=0 && K%2!=0))
   {
        cnt=K;
        j=(a-K)/2;
        l=j;   
        while (cnt>0)
       {
                     tmp[i++]=S[l++];
                      cnt--;
       }
       tmp[i]='\0';
      for(l=j,i=i-1;i>=0;--i)
                 S[l++]=tmp[i];
       printf("%s",S);
   }
}

OUTPUT
example
3

expmale






No comments:

Post a Comment