Average Word Value


TCEA State Programming Contest
April 28, 2001

Problem 9.5 Average Word Value

General Statement: Read a sentence and calculate the average word value for that sentence. Word value is calculated by finding the average of the ASCII values of all of the letters in a word. Average word value is the average of the word values of all of the words in the sentence.

Input: The first line in the data set is an integer that represents the number of sentences that follow. Each sentence is on a separate line.

Output: Output the average rounded to the nearest integer. All letters are upper case.
The output is to be formatted exactly like that for the sample output given below.

Assumptions: All letters are upper case. Any non-letter characters are not part of the word in which they are located. The maximum word length is 10 letters.
The maximum sentence length is 70 characters.

Discussion: Round only the final average, not the averages of the individual words.

Sample Input:
3
HAPPY BIRTHDAY
SUMMER’S ON ITS WAY!
ST. PATRICK’S DAY WAS IN MARCH.

Sample Output:
THE AVERAGE WORD VALUE IS 76
THE AVERAGE WORD VALUE IS 80
THE AVERAGE WORD VALUE IS 77
Solutions:

#include
#include
#include

int main ()
{
int testCase;
scanf (“%d”, &testCase);
getchar ();

while ( testCase– ) {

char sentence [72];
gets (sentence);

int length = strlen (sentence);
double word_value = 0;
int character_count = 0;
int word_count = 1;
double word_average = 0;

for ( int i = 0; i <= length; i++ ) { if ( isalpha (sentence [i]) ) { word_value += sentence [i]; character_count++; } else if ( sentence [i] == ' ' ) { word_average += (word_value/character_count); word_value = 0; character_count = 0; word_count++; } } word_average += (word_value/character_count); printf ("THE AVERAGE WORD VALUE IS %0.lf\n", word_average / word_count); } return 0; } [/sourcecode]

Advertisements

One thought on “Average Word Value

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s