Count words and letters Write a program that reads in a line of text, counts and
ID: 3534830 • Letter: C
Question
Count words and letters
Write a program that reads in a line of text, counts and outputs the number of words in the line and the number of occurrences of each letter.
Define a word to be a string of letters delimited by white space (blank, newline, tab), a comma, or a period. Assume that the input consists only of characters and these delimiters. For purposes of counting letters, case is immaterial.
Output letters in alphabetic order and only output those letters that occur.
Some Help with your Algorithm development:
The word count is carried out with a state machine. We enter with our state variable, inWord set to false, and our word count set to0.
while(input characters is successful)
if we have encountered a blank, newline or a tab,
we set state to false
else if inWord is false,
set state to true
increment word count
lowCase = tolower(inChar);
charCount[int(lowCase) - int('a')]++;
cout << wordCount << " " words" << endl;
for(i = 0; i < 25; i++)
if(charCount[i] != 0)
cout << charCount[i] << " " << char(i + 'a')<< endl;
Comments on the letter count code:
We run tolower() on all characters entered. The data structure for the letter count is a 26-letter int array with indices in the range 0-25, calculated by
index = int(character) - int('a')
as each letter is read in, increment the appropriate array element.
Output of the letter count is a loop running from 0-25, with an if statement that allows output if the array entry isn't zero.
Explanation / Answer
#include <iostream> #include <cctype> using namespace std; void readAndCount (int &numWords, int letterCount[]); // Reads a line of input. Counts the words and the number // of occurrences of each letter. void outputLetterCounts (int letterCount[]); // Prints the number of occurrences of each letter that // appears in the input line. // ========================= // main function // ========================= int main() { int numWords; int letterCount[26]; // stores the frequency of each letter cout << endl; cout << "Enter a line of text.." << endl << endl; readAndCount (numWords, letterCount); cout << endl; cout << numWords << " words" << endl; outputLetterCounts(letterCount); return 0; } // ========================= // Function Definitions // ========================= void readAndCount (int &numWords, int letterCount[]) { char name [20]; int p = 0; int occ = 0; while (p < 20) { if (name[p] == '') { occ = occ+1; } cin >> name[p]; p = p + 1; } } void outputLetterCounts(int letterCount[]) { for (int i = 0; i < 26; i++) { if (letterCount[i] > 0) { cout << letterCount[i] << " " << char('a' + i) << endl; } } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.