C Program to Find Shortest Word From Given Sentence


#include<conio.h>
#include<stdio.h>
#include<string.h>

int main()
{
 char string[100], shortest[30];
 int count = 0, min,i,j,index=0,length;
 clrscr();
 printf("Enter String:\n");
 gets(string);
 length = strlen(string);
 index=0;
 /* Initially set some large value to min */
 min = 100; // This is important
 /* Finding length of shortest word and starting index */
 for( i = 0 ; i< length ; i++)
 {
  if(string[i] != ' ')
  {
   count++;
  }
  else
  {
   if(count < min)
   {
    min = count;
    index = i-min;
   }
   count = 0;
  }
 }
 /* Checking if last word is shortest */
 if(count< min)
 {
  min = count;
  index = length-min;
 }
 /* Using length and index copying shortest word */
 j=0;
 for(i=index;i< index+min;i++)
 {
  shortest[j] = string[i];
  j++;
 }
 /* Inserting NULL character to terminate string */
 longest[j] = '\0';
 printf("Shortest word is: %s\n", shortest);
 printf("And its length is %d",min);
 getch();
 return 0;
}

Output of above program:

Enter Sentence:
Tongue tied and twisted just an earth bound misfit I ↲ 
Shortest word is: I
And its length is: 1


Note: ↲ indicates ENTER is pressed.