Question

6.15 Program 6: Using Arrays to Count Letters in Text 1. Introduction In this program, you...

6.15 Program 6: Using Arrays to Count Letters in Text

1. Introduction

In this program, you will practice working with arrays. Your program will read lines of text from the keyboard and use an array to track the number of times each letter occurs in the input text. You will use the contents of this array to generate a histogram (bar graph) indicating the relative frequencies of each letter entered.

Test cases are available in this document.

Remember, in addition to submitting your code, you MUST complete the Blackboard assignment "Program 6 style assessment" to get all of the points for this program. You can complete this "assignment" by typing a short message indicating you submitted your code through the textbook IDE.

2. Specification

Note: As discussed in class, there are a couple of inefficient brute-force methods to determine which letter is entered. (These prohibited methods are described in Section 3, Hints.) Using either method will incur a 10 point deduction.

Note 2: As also discussed in class, this program should not use strings.

Program Variables

At a minimum, you will need variables in main() to track:

  • The number of times each letter in the alphabet has occurred in the input. These values should be stored in an array, in which the first entry represents the number of 'A' or 'a' characters entered, and the last entry represents the number of 'Z' or 'z' characters entered.
    • For example, if your first input is: Hello World!, the array should hold: {0,0,0,1,1,0,0,1,0,0,0,3,0,0,2,0,0,1,0,0,0,0,1,0,0,0}.
    • The non-zero values indicate the number of 'D', 'E', 'H', 'L', 'O', 'R', and 'W' characters entered, respectively.
    • Note that the character inputs are case-insensitive—uppercase and lowercase letters are treated the same.
  • The maximum number of times any letter occurred—3, in the example above.

These variables are updated every time the user enters the 'R' command followed by a line of input, and reset to 0 every time the user enters the 'C' command. They are used to print the histogram whenever the ‘P’ command is used.

The variables should be updated inside the ReadText() function, and printed using the DrawHist() function.

Program Structure

Your program should repeatedly prompt the user to enter a single character command until the user enters the “quit” command. The program should perform the following operations for the listed commands:

  • 'C', 'c': Clear the letter counts to 0 in preparation for analyzing new text.
  • 'R', 'r': Read one line of text from the keyboard. Update the letter counts appropriately, using the ReadText() function.
  • 'P', 'p': Plot the histogram of letter frequencies in all lines of text entered since the last 'C' command, using the DrawHist() function.
  • 'Q', 'q': Quit—exit the program.

Functions

Your program should contain the functions described below, as well as any other functions you choose to add. Prototypes for these functions should be in prog6_functions.h, while their definitions should be written in prog6_functions.c:

  • void ReadText(int histo[], int *max); Read one line of text from the keyboard, updating the array histo[] with the number of occurrences of each letter of the alphabet. Also, use the pointer max to update the variable holding the number of occurrences of the most frequent letter.
  • void DrawHist(int histo[], int max); Given the array holding the letter counts (histo[]) and the number of occurrences of the most frequent letter (max), plot a histogram of the letter counts. Note that:
    • max helps you determine the height of the histogram, and therefore the number of rows to print.
    • When printing each row, print a vertical bar and a space "| " in the appropriate column if the letter count is large enough to be displayed in that row. Print two spaces otherwise.
    • Remember to leave spaces between columns—your output should line up exactly as shown in the test cases.
    • Remember that you are printing from the top of the histogram to the bottom—that fact will affect the design of this function.

See the test cases that demonstrate the proper format for input and output.

3. Hints

ASCII values

Recall that each character has a corresponding integer value, according to the ASCII standard. You may find it useful to work directly with ASCII values in this program, rather than testing if each input character matches a particular letter. 'A' has the ASCII value 65; 'a' has the ASCII value 97.

Character functions

You may find the following built-in functions from the <ctype.h> library useful. Remember that int and char data types are compatible:

  • int isalpha(int ch): This function returns a non-zero value if ch is a letter of the alphabet, and zero otherwise.
    • For example, isalpha('Q') returns a non-zero value; isalpha('3') returns 0.
  • int tolower(int ch): If ch is an uppercase letter, this function returns the lowercase version. Otherwise, tolower() returns the original value of ch.
    • For example, tolower('Q') returns 'q'; tolower('a') returns 'a'.
  • int toupper(int ch): If ch is a lowercase letter, this function returns the uppercase version. Otherwise, tolower() returns the original value of ch.
    • For example, toupper('q') returns 'Q'; toupper('A') returns 'A'.

Prohibited brute force methods

Brute force methods are inefficient solutions to problems. Such a method can be used to determine which letter was entered and update the appropriate array entry, but I want you to find a more efficient solution. Using a brute force method like the following will therefore incur a 10 point deduction.

Again, each of the following is an example of what NOT to do:

  • Large switch (or if) statement: one case for each letter, with array index as a known constant in each case:
switch(ch) {            // ch = input char
case ‘A’: case ‘a’:
    // modify histo[0]
    break;
case ‘B’: case ‘b’:
    // modify histo[1]
    break;

    // Remainder of cases
}
  • Loop: compares input character against all possible letters, using loop index as array index:
char test = ‘A’;
for (i = 0; i < 26; i++) {
    if (ch == test)
        // modify histo[i]
    test++;     // Change test 
}                //  to next letter

Note: Each brute force method essentially compares the input character against all possible letters. However, once you know the input character is a letter, you do not need to compare it to anything to determine what array entry to update! There’s a simple “transformation” between the ASCII value of each letter and the corresponding index in the histogram array.

1 0
Add a comment Improve this question Transcribed image text
Answer #1

find the java code to count the number of letters, lines, space and paragraph in a text:-

import java.io.*; 

public class Test 
{ 
        public static void main(String[] args) throws IOException 
        { 
                File file = new File("Path_of _file"); 
                FileInputStream fileStream = new FileInputStream(file); 
                InputStreamReader input = new InputStreamReader(fileStream); 
                BufferedReader reader = new BufferedReader(input); 
                
                String line; 

                int countWord = 0; 
                int sentenceCount = 0; 
                int characterCount = 0; 
                int paragraphCount = 1; 
                int whitespaceCount = 0; 
                
                while((line = reader.readLine()) != null) 
                { 
                        if(line.equals("")) 
                        { 
                                paragraphCount++; 
                        } else { 
                                characterCount += line.length(); 
                                
                                String[] wordList = line.split("\\s+"); 
                                
                                countWord += wordList.length; 
                                whitespaceCount += countWord -1; 

                                String[] sentenceList = line.split("[!?.:]+"); 
                                
                                sentenceCount += sentenceList.length; 
                        } 
                } 
                
                System.out.println("Total word count = " + countWord); 
                System.out.println("Total number of sentences = " + sentenceCount); 
                System.out.println("Total number of characters = " + characterCount); 
                System.out.println("Number of paragraphs = " + paragraphCount); 
                System.out.println("Total number of whitespaces = " + whitespaceCount); 
        } 
} 
Add a comment
Know the answer?
Add Answer to:
6.15 Program 6: Using Arrays to Count Letters in Text 1. Introduction In this program, you...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This is for C++ Write a program that reads in a sequence of characters entered by...

    This is for C++ 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...

  • Topics: Arrays in C. For this assignment, you will write a C program that uses its...

    Topics: Arrays in C. For this assignment, you will write a C program that uses its first command line parameter to compute and display a histogram of characters that occur in it. Requirements: Your program must compile and run correctly using the gcc compiler on ale. You must write the corresponding function definitions for the following function prototypes: // set all elements of the histogram to zero void init_histogram(int histo[]); // construct the histogram from string void cons_histogram(char string[], int...

  • c# csci312: character counter - vector design a program that reads in an ascii text file...

    c# csci312: character counter - vector design a program that reads in an ascii text file (provided) ... Your question has been answered Let us know if you got a helpful answer. Rate this answer Question: C# CSCI312: Character Counter - Vector Design a program that reads in an ASCII text file (provide... C# CSCI312: Character Counter - Vector Design a program that reads in an ASCII text file (provided) and creates an output file that contains each unique ASCII...

  • Using basic c++ write 2 separate codes for this assignment. Program #1 Write a program that...

    Using basic c++ write 2 separate codes for this assignment. Program #1 Write a program that calculates the average of a group of test scores, where the lowest score in the group is dropped. It should use the following functions. • void getScore() should ask the user for a test score, store it in the reference parameter variable, and validate it. This function should be called by the main once for each of the five scores to be entered. •...

  • C Program In this assignment you'll write a program that encrypts the alphabetic letters in a...

    C Program In this assignment you'll write a program that encrypts the alphabetic letters in a file using the Vigenère cipher. Your program will take two command line parameters containing the names of the file storing the encryption key and the file to be encrypted. The program must generate output to the console (terminal) screen as specified below. Command Line Parameters Your program must compile and run from the command line. The program executable must be named “vigenere” (all lower...

  • I need help programming this program in C. 1.) Write a program that reads a message,...

    I need help programming this program in C. 1.) Write a program that reads a message, then checks whether it's a palindrome (the letters in the message are the same from left to right as from right to left), example is shown below: Enter a message: He lived as a devil, eh? Palindrome Enter a message: Madam, I am Adam. Not a Palindrome 2.) Ignore all characters that aren't letters. Use integer variables to keep track of positions in the...

  • I need eclipse code for : Write a program that analyzes text written in the console...

    I need eclipse code for : Write a program that analyzes text written in the console by counting the number of times each of the 26 letters in the alphabet occurs. Uppercase and lowercase letters should be counted together (for example, both ‘A’ and ‘a’ should count as an A). Any characters that are not letters should be ignored. You must prompt the user to enter the text to be analyzed. Then, for any letter that appeared at least once...

  • Intro to Programming in C – Large Program 1 – Character/ Number converter Assignment Purpose: To...

    Intro to Programming in C – Large Program 1 – Character/ Number converter Assignment Purpose: To compile, build, and execute an interactive program with a simple loop, conditions, user defined functions and library functions from stdio.h and ctype.h. You will write a program that will convert characters to integers and integers to characters General Requirements • In your program you will change each letter entered by the user to both uppercase AND lowercase– o Use the function toupper in #include...

  • Write a C program that takes two sets of characters entered by the user and merge...

    Write a C program that takes two sets of characters entered by the user and merge them character by character. Enter the first set of characters: dfn h ate Enter the second set of characters: eedtecsl Output: defend the castle Your program should include the following function: void merge(char *s3, char *s1, char *s2); The function expects s3 to point to a string containing a string that combines s1 and s2 letter by letter. The first set might be longer...

  • u also need to store the letters' ASCII number in the freq array 4. [8] Write...

    u also need to store the letters' ASCII number in the freq array 4. [8] Write a C function with prototype · void letter_freq(const char word[], int freq []); This function computes the number of appearances of each letter in the string word and stores them in array freq of size 26. The letters are the 26 letters of the Latin alphabet whose ASCII values are in the range 97-122 for the lower case letters, and in the range 65-90...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT