A simple C program to print the second largest word of a input string using array of pointers
/* to find the
second largest word in the sentence and to print it */
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
char
str[40],*x[10];
int
i=0,j=0,tmp,len,t,k,l,leng[20];
printf("\n
Enter a string:");
gets(str);
len=strlen(str);
for(i=0;i<=len;i++)
{
k=i;
tmp=0;
while(str[k]!=' ' && str[k]!='\0')
{
k++;
tmp++;
if(str[i]=='\n')
break;
}
x[j]=(char
*)malloc(tmp*sizeof(char));
l=0;
for(t=i;t<tmp+i;t++)
{
*(x[j]+l)=str[t];
l++;
}
*(x[j]+l)='\0';
i=k;
j++;
}
for(i=0;i<j;i++)
{
leng[i]=(strlen(x[i]));
//printf("\n [%d]
%s",leng[i],x[i]);
}
for(i=0;i<j-1;i++)
{
for(k=i+1;k<j;k++)
{
if(leng[i]<leng[k])
{
tmp=leng[k];
leng[k]=leng[i];
leng[i]=tmp;
}
}
}
tmp=leng[1];
if(tmp==leng[0])
{
for(i=0;i<j;i++)
{
if(tmp==leng[i])
continue;
else
{
tmp=leng[i];
break;
}
}
}
puts("\n
Second longest words is/are:");
for(i=0;i<j;i++)
{
if(tmp==strlen(x[i]))
printf(" %s ",x[i]);
}
return 0;
}
No comments:
Post a Comment