To find the smallest and largest string in a sentence
Question:
Write a program to find smallest and largest string in a given sentence.
Logic:
- Get the input string from the user.
- Then check the smallest string and store into an array.
- And check the largest string and store into another array.
- Then prints the smallest and largest string.
Algorithm:
- Get the input string from the user.
- Then check for space it denotes ending of word.
- Store the word into small and large array.
- And compare all other word with the current word.
- If the word larger then large and swaps the word in large array.
- If the word smaller then small and swaps the word in small array.
- When the string reaches the last word then prints the large and small word.
Program:
include<stdio.h> void main() { /* a->input string small->stores small word in the string large->stores large word in the string temp->temporarily stores word p->length of small word q->length of large word c->index of each word m->temporarily stores length of each word n->stores length of each word */ char a[100],small[20],temp[20],large[20]; int i,j,k=0,c=0,p=0,q=0,m,n; clrscr(); printf("enter the string:"); gets(a); n=strlen(a); for(i=0;i<=n;i++) { /*when reaches space it denotes end of the word and null denotes end of the string*/ if(a[i]==' '||a[i]=='\0') { for(j=c;j<i;j++) { temp[k]=a[j]; //each word stores into an array temporarily if(c==0) //for first time only the first word copied to small and large arrays { small[k]=a[j]; large[k]=a[j]; } k++; //index of temp variable } m=i-c; //length of each word if(c==0) //length of small and large { p=m; q=m; } else if(m<p) //if temp word is smaller than word already stroed in the small array { for(j=0;j<m;j++) //copies temp to small { small[j]=temp[j]; } p=m; } else if(m>q) //if temp word is larger than word already stored in the large array { for(j=0;j<m;j++) //copies temp to large { large[j]=temp[j]; } q=m; } k=0; c=i+1; } } printf("The smallest word in the given string is: "); for(i=0;i<p;i++) { printf("%c",small[i]); } printf("\nThe largest word in the given string is: "); for(i=0;i<q;i++) { printf("%c",large[i]); } getch(); }