Question

Note: Do not use classes or any variables of type string to complete this assignment Write...

Note: Do not use classes or any variables of type string to complete this assignment

Write a program that reads in a sequence of characters entered by the user and terminated by a period ('.'). Your program should allow the user to enter multiple lines of input by pressing the enter key at the end of each line. The program should print out a frequency table, sorted in decreasing order by number of occurences, listing each letter that ocurred along with the number of times it occured. All non-alphabetic characters must be ignored. Any characters entered after the period ('.') should be left in the input stream unprocessed. No limit may be placed on the length of the input.

Use an array with a struct type as its base type so that each array element can hold both a letter and an integer. (In other words, use an array whose elements are structs with 2 fields.) The integer in each of these structs will be a count of the number of times the letter occurs in the user's input.

Let me say this another way in case this makes more sense. You will need to declare a struct with two fields, an int and a char. (This should be declared above main, so that it is global; that is, so it can be used from anywhere in your program.) Then you need to declare an array (not global!) whose elements are those structs. The int in each struct will represent the number of times that the char in the same struct has occurred in the input. This means the count of each int should start at 0 and each time you see a letter that matches the char field, you increment the int field.

Don't forget that limiting the length of the input is prohibited. If you understand the above paragraph you'll understand why it is not necessary to limit the length of the input.

The table should not be case sensitive -- for example, lower case 'a' and upper case 'A' should be counted as the same letter. Here is a sample run:

Enter a sequence of characters (end with '.'): do be Do bo. xyz

Letter:    Number of Occurrences
     o     3
     d     2
     b     2
     e     1

Note: Your program must sort the array by descending number of occurrences, using a selection sort. Be sure that you don't just sort the output. The array itself needs to be sorted.

Submit your source code and some output to show that your code works.

Hints: Students seem to get hung up on the requirement that the user can enter multiple lines of input and that you should leave characters after the period in the input stream. The intention of these requirements (believe it or not) is to steer you toward a better and simpler solution, so please don't get too hung up on them! Another way of stating the requirement is this: just keep reading characters one at a time, ignoring newline characters (that is, treating them just like any other non-alphabetic character), until you get to a period.

You will definitely want to pay close attention to section 9.2 from the text while tackling this assignment. In my solution I use cin.get(ch), isalpha(ch), and tolower(ch).

When determining which array element to access you may want to do some arithmetic that involves characters. For example, saying array[ch - 'a'] will access array[0] if ch is 'a', array[1] if ch is 'b', and so on. Let me know if you need further explanation on this concept. Although it is not completely safe, you should assume for this assignment that the ASCII character set is being used. (This will simplify your code somewhat.)

Note that your struct should be declared above main, and also above your prototypes, so that your parameter lists can include variables that use the struct as their base type. It should be declared below any global consts.

Please add function comments.

Homework Answers

Answer #1

#include <iostream>
#include <iomanip>
using namespace std;


// Defines the struct for the array. Each array will have a 'letter' and a number that counts the 'frequency' of that letter in the user's input.
struct ArrayStruct
{
   int frequency;
   char letter;
};

  


const int NUM_LETTERS = 25; // The size of the array will be 26. Each element of the array will represent a letter of the alphabet.

void createArray(ArrayStruct charCount[]);
void readInput(ArrayStruct charCount[]);
void sortArray(ArrayStruct charCount[]);
int indexOfLargest(const ArrayStruct charCount[], int startingIndex);
void printArrayExcept(ArrayStruct charCount[], int numToSkip);

int main()
{
   ArrayStruct charCount[NUM_LETTERS];
   createArray(charCount);
   readInput(charCount);
   sortArray(charCount);
   printArrayExcept(charCount, 0);
}

// Fills the initially empty array 'charCount'. Puts a different letter and its starting frequency count 0 in its own array element. Element 0 of the array will be for letter 'a', element 1 will be for letter 'b', and so on.
void createArray(ArrayStruct charCount[])
{
   for (int count = 0; count < NUM_LETTERS; count++) {
       charCount[count].letter = (char)(count + 'a');
       charCount[count].frequency = 0;
   }
}

// Reads the user input. As long as the inputted character is not a period, this function will check to see if the character is an alphebet letter, put it in its lower case form, and the increase the
// frequency count of the array element in the array 'charCount' with that letter.
void readInput(ArrayStruct charCount[])
{
   cout << "Enter a sequence of characters (end with '.'): " ;
   char ch;
   while (ch != '.') {
       cin.get(ch);
       if (isalpha(ch)) {
           ch = tolower(ch);
           charCount[ch - 'a'].frequency++;
       }
   }
}


// Sorts the array 'charCount' in descending order of frequency of each letter. This function is based on the code for the selection sort function in Lesson 10.6.
void sortArray(ArrayStruct charCount[])
{
   for (int count = 0; count < NUM_LETTERS; count++){
       swap(charCount[indexOfLargest(charCount, count)],
           charCount[count]);
   }  
}


// Finds the element in the array 'charCount', starting at the 'startingIndex', that has the largest frequency count for its letter and returns the index of that element.
// This function is based on the code for the indexOfSmallest function in Lesson 10.6.
int indexOfLargest(const ArrayStruct charCount[], int startingIndex)
{
   int targetIndex = startingIndex;
  
   for (int count = startingIndex + 1; count < NUM_LETTERS; count++){
       if (charCount[count].frequency > charCount[targetIndex].frequency){
           targetIndex = count;
       }
   }
   return targetIndex;
}


// Prints the elements in the array 'charCount'. Prints the letters that were inputted along with each one's frequency, as long as the frequency count of that letter does not equal the 'numToSkip'.
void printArrayExcept(ArrayStruct charCount[], int numToSkip)
{
   cout << endl;
   cout << "Letter:" << "    " << "Number of Occurrences" << endl;
   for (int count = 0; count < NUM_LETTERS; count++) {
       if (charCount[count].frequency != numToSkip) {
           cout << setw(6) << charCount[count].letter << "     " << charCount[count].frequency << endl;
       }
   }
}


Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
WRITE C++ PROGRAM FOR 1,2,3,4 PARTS of question, DO ADD COOMENTS AND DISPLAY THE OUTPUT OF...
WRITE C++ PROGRAM FOR 1,2,3,4 PARTS of question, DO ADD COOMENTS AND DISPLAY THE OUTPUT OF A RUNNING COMPILER QUESTION: 1) Fibonacci sequence is a sequence in which every number after the first two is the sum of the two preceding ones. Write a C++ program that takes a number n from user and populate an array with first n Fibonacci numbers. For example: For n=10 Fibonacci Numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 2): Write...
Write Java program Lab51.java which takes in a string from the user, converts it to an...
Write Java program Lab51.java which takes in a string from the user, converts it to an array of characters (char[] word) and calls the method: public static int countVowels(char[]) which returns the number of vowels in word. (You have to write countVowels(char[]) ).
Part 1 Write a program that reads a line of input and display the characters between...
Part 1 Write a program that reads a line of input and display the characters between the first two '*' characters. If no two '*' occur, the program should display a message about not finding two * characters. For example, if the user enters: 1abc*D2Efg_#!*345Higkl*mn+op*qr the program should display the following: D2Efg_#! 1) Name your program stars.c. 2) Assume input is no more than 1000 characters. 3) String library functions are NOT allowed in this program. 4) To read a...
C Program Write a program to count the frequency of each alphabet letter (A-Z a-z, total...
C Program Write a program to count the frequency of each alphabet letter (A-Z a-z, total 52 case sensitive) and five special characters (‘.’, ‘,’, ‘:’, ‘;’ and ‘!’) in all the .txt files under a given directory. The program should include a header count.h, alphabetcount.c to count the frequency of alphabet letters; and specialcharcount.c to count the frequency of special characters. Please only add code to where it says //ADDCODEHERE and keep function names the same. I have also...
Write a C program that prompts the user to enter a line of text on the...
Write a C program that prompts the user to enter a line of text on the keyboard then echoes the entire line. The program should continue echoing each line until the user responds to the prompt by not entering any text and hitting the return key. Your program should have two functions, writeStr and readLn, in addition to the main function. The text string itself should be stored in a char array in main. Both functions should operate on NUL-terminated...
Assignment #4 – Student Ranking : In this assignment you are going to write a program...
Assignment #4 – Student Ranking : In this assignment you are going to write a program that ask user number of students in a class and their names. Number of students are limited to 100 maximum. Then, it will ask for 3 test scores of each student. The program will calculate the average of test scores for each student and display with their names. Then, it will sort the averages in descending order and display the sorted list with students’...
Write a program that accepts an input string from the user and converts it into an...
Write a program that accepts an input string from the user and converts it into an array of words using an array of pointers. Each pointer in the array should point to the location of the first letter of each word. Implement this conversion in a function str_to_word which returns an integer reflecting the number of words in the original string. To help isolate each word in the sentence, convert the spaces to NULL characters. You can assume the input...
Write a program that prompts the user to input a string and outputs the string in...
Write a program that prompts the user to input a string and outputs the string in uppercase letters. (Use dynamic arrays to store the string.) my code below: /* Your code from Chapter 8, exercise 5 is below. Rewrite the following code to using dynamic arrays. */ #include <iostream> #include <cstring> #include <cctype> using namespace std; int main() { //char str[81]; //creating memory for str array of size 80 using dynamic memory allocation char *str = new char[80]; int len;...
IN C++ Write a program named printStringReverse.cpp to read in a C-Style sting. Print the string...
IN C++ Write a program named printStringReverse.cpp to read in a C-Style sting. Print the string forward and then backward using pointer increment and decrement. Declare the C-Style string as following: char s[50]; Read the string as follows; cin >> s; Write the following code to get the actual number of characters from your string. int count=0; while (s[count] != NULL) { count++; } count contains the actual length of your string since we declared the array to hold a...
1. a)Write a program that displays the name and address of your college in C# b)Write...
1. a)Write a program that displays the name and address of your college in C# b)Write a program that prompts the user for his name and average monthly visa bill. The program displays his name and his annual visa bill. You must match the format exactly: Name: Justin Bieber Annual Visa Bill: $12,000.00 Hint: annual bill = monthly bill * 12 c)Write a program that prompts the user for a letter. The program prints the letter and the number equivalent....
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT