Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Only use preprocessor <stdio.h> Write a program that calculates the average word

ID: 3564873 • Letter: O

Question

Only use preprocessor <stdio.h> Write a program that calculates the average word length for a sentence. Your program should consider a punctuation mark to be part of the word to which it is attached unless it is a comma, period, or exclamation point. Display the average word length to one decimal place. For instance, in the sentence "And. that's the way the cookie crumbles.", the first word ("And.") contains 3 characters, the second word "that's" has 6 characters, and the last word ("crumbles.") has 8 characters. Specifications: Prompt the user to enter a sentence. Use the getchar() function and a while loop to read in characters one at a time and perform your calculations (keep track of the total number of words in a sentence, the number of letters in a word, whether you need to ignore some punctuation, etc.). Then print a second prompt asking the user to press the Enter key to continue. Once the Enter key is pressed, the results should be displayed to the screen. Here are a couple of examples...

Explanation / Answer

#include <stdio.h>
double compute_average_word_length(const char *sentence);
int main(int argc, char *argv[])
{
if (argc != 2) {
printf(stderr, "Usage: %s "Enter a sentence in quotes." ", argv[0]);
return 1;
}
printf("%.2f ", compute_average_word_length(argv[1]));
return 0;
}
double compute_average_word_length(const char *sentence)
{
register bool in_word = false;
double chars, words, apostrophes;
int open_quotes, other_single_quotes;
open_quotes = other_single_quotes = 0;
chars = words = apostrophes = 0.0;
for (const char *c = sentence; *c; c++) {
if (*c == ''') {
if (in_word)
/* could be an apostrophe or a close-quote right after a word */
other_single_quotes++;
else {
if (open_quotes % 2 > 0)
/*
Count of open-quotes is odd, so we're looking for a close quote.
This one is placed after punctuation or an extra space after a word.
*/
other_single_quotes++;
else
open_quotes++;
}
} else if (isalnum(*c) || *c == '-' || *c == '_') {
in_word = true;
chars++;
} else if (in_word) {
/* we just left the word: we won't be here in the case of initial or multiple spaces */
in_word = false;
words++;
}
}
/* did we terminate on a word character? */
if (in_word)
words++;
/* adjust char count for apostrophes, but only if the single quotes balance out */
if (other_single_quotes >= open_quotes)
apostrophes = (double) (other_single_quotes - open_quotes);
chars += apostrophes;
return chars / words;
}