63.2k views
2 votes
You are given a C program "q2.c" as below. This program is used to calculate the average word length for a sentence (a string in a single line): Enter a sentence: It was deja vu all over again. Average word length: 3.42 For simplicity, the program considers a punctuation mark to be part of the word to which it is attached. And it displays the average word length to two decimal places.

1 Answer

1 vote

Answer:

  1. #include <stdio.h>
  2. #include <string.h>
  3. int main()
  4. {
  5. char sentence[100];
  6. int i;
  7. int wordCount = 1;
  8. int charCount = 0;
  9. float averageLength;
  10. printf("Enter a sentence: ");
  11. gets(sentence);
  12. for(i = 0; i < strlen(sentence); i++){
  13. if(sentence[i] != ' '){
  14. charCount++;
  15. }else{
  16. wordCount++;
  17. }
  18. }
  19. averageLength = (float)charCount / wordCount;
  20. printf("Average word length: %.2f", averageLength);
  21. return 0;
  22. }

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).

User Joel G Mathew
by
2.9k points