This article to share with you is to write a program that can calculate the frequency of each letter of input characters, specifically as follows
Let me show you the final results:
When I just took over the topic, I thought it was complicated, because there are 26 letters in the case, lowercase a~z, uppercase a~z
But, whether in uppercase or lowercase, there are only 26 letters, here, when we enter uppercase letters, we convert them to lowercase, OK.
Uppercase letters are converted to lowercase letters, and there is a handy function tolow (), in Ctype.h, at the end of the details article.
Read the previous article "C Language: Calculation of the number of input characters" in the use of arrays to count the length of words, in the count of the number of letters, still can, but some "small skills."
Case conversion and calculation
if (Isalpha (c))/* details see
at the end of article/{c = ToLower (c);//uppercase to lowercase
++char_count[c-' a '];
}
The above code will be 26 letters to the frequency of the statistics (all exist in the array), and then print the histogram, what is the histogram, that is, the Ventura, look up.
Because you want to draw a histogram, you use two for loop statements, and by looking at it you know that the number of rows in the histogram is determined by Max.
Max how to ask, look at the following code:
max = 0; Initialize
/* Find the most frequently occurring letter
/for (x = 0; x < + + +)
{
if (Char_count[x] > Max)
{
max = Char_ COUNT[X];
printf ("Max is%d", max);
}
Now Max knows, to draw the histogram:
/* Print histogram * * for
(; max > 0; max--)
{for
(x = 0; x < +)
{
if (Char_count[x] >= max)
{
putchar (' x ');
}
else
Putchar (');
}
Putchar (' \ n ');
}
Now all OK, still a horizontal axis, otherwise we know what each column represents is which letter it:
/* Print subscript, that is, abcdefghijklml....*/for
(x = 0; x < + x + +)
{
Putchar (' a ' +x);
}
Complete code:
#include <stdio.h> #include <ctype.h> main () {int x;//array subscript variable, see Code for details int Max; The most frequently occurring letter int char_count[26];
26 alphanumeric occurrences of Word count char C;
/* Initialize the array because we haven't entered it yet, so the a~z are all 0 */for (x= 0 x < + x + +) {Char_count[x] = 0; while ((c = GetChar ())!= EOF) {if (Isalpha (c))/* Details see end of article/{c = ToLower (c);//uppercase to lowercase ++c
har_count[c-' a ']; } max = 0; Initialize/* Find the most frequently occurring letter/for (x = 0; x < + + +) {if (char_count[x] > max) {max = Char_count
[x];
printf ("Max is%d", max); }//* print histogram */for (; max > 0; max--) {for (x = 0; x < + x + +) {if (Char_count[x] >=
Max) {Putchar (' x ');
else Putchar (');
} putchar (' \ n ');
/* Print subscript, that is, abcdefghijklml....*/for (x = 0; x < + x + +) {Putchar (' a ' +x);
return 0; }
Ps:
The above is the calculation of input characters each letter frequency of the overall problem solving ideas, I hope to help you learn.