Given an input string S, centre justify the string. There will be neither preceding characters before the string S nor suffix characters after the string S. The output should be centre-justified in a line of width 64 characters, followed by a newline.
Note:
1. If S has an odd number of characters then the number of preceding 'space' should be one more than the number of trailing 'space'
2. If S has an even number of characters then the number of preceding 'space' should be equal to the number of trailing 'space'
#include<stdio.h>
#include<string.h>
int main()
{
int ch,i;
char s[64];
char p[66];
char *ptr1;
for(i=0;i<64;i++) /* initialize the array with white space */
p[i]=32;
p[i]='\n'; /* store _ just before null character */
p[i+1]='\0';/* for ease of use strings initilize null character at the end */
ch=getchar(); /* read the string till getting 'enter' from user */
i=0;
while(ch!='\n')
{
s[i]=ch;
i++;
ch=getchar();
}
s[i]='\0'; /* assign null character at the end of input */
int len=strlen(s); /* find the length of input string */
char *j;
int k;
if(len%2==0) /*if lenght is even numbered */
{
k=0;
ptr1=(char *)(p+(32*sizeof(char))-(len/2));
/* copy input at the appropriate position in p */
for(j=ptr1;j<=(ptr1+len-1);j++)
{
*j=s[k];
k++;
}
}
else /* if length is odd number*/
{
k=-1;
ptr1=(char *)(p+(32*sizeof(char))-((len-1)/2));
/* copy input at the appropriate position in p */
for(j=ptr1;j<=(ptr1+len-1);j++)
{
k++;
*j=s[k];
}
}
printf("%s",p); /* print the string */
return 0;
}
Sample input and output:
Programming is fun
Programming is fun