Answer:
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- char sentence[100];
- int i;
- int wordCount = 1;
- int charCount = 0;
- float averageLength;
-
- printf("Enter a sentence: ");
- gets(sentence);
-
- for(i = 0; i < strlen(sentence); i++){
- if(sentence[i] != ' '){
- charCount++;
- }else{
- wordCount++;
- }
- }
-
- averageLength = (float)charCount / wordCount;
- printf("Average word length: %.2f", averageLength);
-
- return 0;
- }
Step-by-step explanation:
Firstly we need to import the string.h library as we need to use strlen method to estimate the length of the input string (Line 2).
To estimate the average word length for an input sentence, we can calculate the total of characters in the sentence and then divide it by the total number of words. To do so, we first get the input sentence from the user (Line 11-12). Next, use a for loop to traverse through the sentence character by character and check if the character is not a space ' ', increment charCount by one. Whenever there is a space, this mark an end of a word and therefore increment wordCount by one (Line 18).
After the loop, we can calculate the average word length by dividing the charCount by wordCount and print the output to two decimal places (Line 22- 23).