// Elaine Torrez CS1A
// _____________________________________________________________
//
// CALCULATE AVERAGE LETTERS PER WORD
// _____________________________________________________________
// This program prompts the user to enter a sentence. It then
// determines the number of words and the total number of letters
// in the sentence. Finally, it calculates and displays the
// average number of letters in each word.
// _____________________________________________________________
// INPUT
// userStr : The sentence entered by the user
//
// OUTPUT
// words : Number of words in the sentence
// letters : Number of letters (A–Z / a–z)
// average : Average number of letters per word
// _____________________________________________________________
#include <iostream>
using namespace std;
// FUNCTION PROTOTYPES
int countWords(const char *str);
int countLetters(const char *str);
int main()
{
/****************************************************
* VARIABLE DECLARATIONS
****************************************************/
const int SIZE = 200;
char userStr[SIZE]; // INPUT sentence
int words; // Number of words
int letters; // Number of letters
float average; // Average letters per word
/****************************************************
* INPUT
****************************************************/
cout << "Enter a sentence: ";
cin.getline(userStr, SIZE);
/****************************************************
* PROCESS
****************************************************/
words = countWords(userStr);
letters = countLetters(userStr);
if (words > 0)
average = static_cast<float>(letters) / words;
else
average = 0;
/****************************************************
* OUTPUT
****************************************************/
cout << "\nWords : " << words << endl;
cout << "Letters : " << letters << endl;
cout << "Average : " << average << endl;
return 0;
}
// *************************************************************
// countWords
// -------------------------------------------------------------
// Returns the number of words in a C-string. A word is counted
// when transitioning from a space to a non-space character.
// *************************************************************
int countWords(const char *str)
{
int count = 0;
bool inWord = false;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] != ' ' && !inWord)
{
inWord = true;
count++;
}
else if (str[i] == ' ')
{
inWord = false;
}
}
return count;
}
// *************************************************************
// countLetters
// -------------------------------------------------------------
// Returns the number of alphabetic letters (A–Z, a–z) in
// a C-string. Spaces and punctuation are ignored.
// *************************************************************
int countLetters(const char *str)
{
int count = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if ((str[i] >= 'A' && str[i] <= 'Z') ||
(str[i] >= 'a' && str[i] <= 'z'))
{
count++;
}
}
return count;
}