Write a C program to print Largest and Smallest Word from a given sentence. If there are two or more words of same length then the first one is considered.
Answers
Sample C program
#include<stdio.h>
#include<string.h>
int main()
{
int i = 0, j = 0, flag = 0, b, longest = 0, shortest = 0, big = 0, small = 0;
char s[100] = {0}, substr[100][100] = {0},c;
printf("Enter a string: ");
gets(s);
while(s[flag]! = '\0')
{
j = 0;
while(s[flag]! = ' ' && s[flag]!= '\0')
{
substr[i][j] = s[flag];
flag++;
j++;
}
substr[i][j]='\0';
i++;
if(s[flag]!='\0')
{
flag++;
}
}
int sentence = i;
big = strlen(substr[0]);
small = strlen(substr[0]);
for(i = 0; i < sentence; i++)
{
b = strlen(substr[i]);
if(b > big)
{
big = b;
shortest = i;
}
if(b < small)
{
small = b;
longest = 0;
}
}
printf("Longest word is:%s", substr[shortest]);
printf("Smallest word is:%s",substr[longest]);
return 0;
}
Output:
Enter string:
Welcome to brainly.
Longest word is: Welcome
Smallest Word is: to
Hope it helps!