Hi guys. For my first help request on these boards, I would like to explain the following problem I've been having. It deals with arrays in C.
Program Question:
Write a program that prompts the user to enter text at the terminal. When the user finishes entering text, he or she should enter the appropriate end-of-file character to terminate input. The program should count the frequency of each letter of the alphabet. The program should not distinguish an uppercase letter from a lowercase letter. When the user finishes inputting text, the program should display each letter and its count.
The question provides the following hint:
Declare an array of counters, one for each letter. Use the letter itself as the subscript that determines which array element to increment. To do this, the program must convert the letter to the corresponding subscript. Remember that the decimal ASCII values of the lowercase letters are 97 to 122 and the uppercase letter are 65 to 90.
Here's what I have for my code so far:
Code:
/* Prob 11-9
* Created by Yuriy Mokriy
*/
#include <stdio.h>
#define ALPHABET_TOTAL 25 /* The total number of letters in the alphabet */
main()
{
int text[ALPHABET_TOTAL] = {0}, /* Array sized 26, acting as counters for all characters 'a' .. 'z' (case insensitive) */
text_input, /* Reads in the text input as characters */
ASCII_count, /* The ASCII numerical representation of letters in the alphabet */
alpha; /* boolean "flag" which turns to 0 (false) in case of a non-alpha character */
/* Get input */
printf("\nPlease enter text. Terminate program using Ctrl+Z: ");
text_input = getchar();
while( text_input != EOF )
{
alpha = 1;
/* If input is alphabetical, convert to a number 0-25 so that it can be used as an array index locator */
if( text_input >= 'a' && text_input <= 'z' )
text_input -= 'a';
else if( text_input >= 'A' && text_input <= 'Z' )
text_input -= 'A';
/* Non-alphabetical character, set the alpha flag to false */
else
alpha = 0;
/* Increment the appropriate counter in the text array as long as the character is alphabetical */
if(alpha)
text[text_input]++;
/* Get input for next loop iteration */
text_input = getchar();
}
/* Display results */
for (ASCII_count = 65; ASCII_count <= 90; ASCII_count++)
printf("\nTotal %c or %c: %d", ASCII_count, ASCII_count + 32, text[text_input]);
}
A few notes of interest:
* The "end-of-file" character the program is referring to is the "Ctrl+Z" character that is used to terminate the program and display the results.
* The program works fine in everything except the actual letter instance incrementation.
* This question forbids use of pointers, strings, memory allocation, and user defined structures. Only character input is allowed.
Arrays have been kicking my butt for a long time in C. I understand how they work and what their purpose is but when the program refuses to execute the way it is intended, it can lead to some real frustration.
Any help is appreciated in this. Thanks.
