Recently I read "second edition of C language programming" and did the above exercises.
1. Write a program to print the histogram of the word length in the input.
2. Write a program to print the histogram of the occurrence frequency of each character in the input.
First, if you do not enter a word, you need to enter a space, enter a word, enter a space, and then input it cyclically. When a sentence is input, you need to separate the line and start with another paragraph.
Example:
I am a studen
The length of the 1st words is 1.
The length of 2nd words is 2.
The length of the 3rd words is 1.
The length of the 4th words is 6.
However, each time you enter a word, you need to separate it with spaces. Then, in the process of input and writing, you need to judge the word. For details, see the code.
Through Wikipedia, the maximum length of a word is currently 30, and there is a long length of about 225 letters, but we generally do not need it.
Set the maximum length of the letter MAXWORD to 30. If you like it, you can set it to any length.
Create a word length array, wl [].
Maximum array size: wl [MAXWORLD]
Set all values in the word length array to 0.
Int I;
For (I = 1; I <= MAXWORD; I ++)
Wl [I] = 0;
Why?
This is what I think when I encounter this question. Every time I input a word, I keep its length in an array.
So I wrote it for a long time.
Later, I did not write it. I took the original notes and looked at it. I thought it would be much easier.
I will be 1 ~ long ~ 30 letters, which are classified as 1, 2, and 3 respectively, are then placed into an array for them to be saved.
Example:
The internet Word is 8 characters long, so I will put it into the array wl [8],
If there is still the same length in wl [8], the wl [8] value will be + 1.
Therefore, it should be written as ++ wl [8].
Now we understand the concept. We can write it like this.
# Include <stdio. h>
# Define MAXWORD 30 // maximum length of a word
# Define IN 1 // there is no space IN the word
# Define OUT 0 // OUT of a word, that is, a space is encountered.
/* Word length => wl word length abbreviation */
Int wl ()
{
Int c;
Int I;
Int nc;
Int state; // state: IN or OUT;
Int overflow; // Number of MAXWORD words
Int wl [MAXWORD]; // The length is 1 ~ Length statistics of 30 characters
State = OUT;
Nc = 0;
Overflow = 0;
For (I = 1; I <MAXWORD; ++ I)
Wl [I] = 0;
While (c = getchar ())! = EOF)
If (c = ''| c = '\ n' | c =' \ t ')
{
State = OUT;
If (nc> 0)
If (nc <MAXWORD)
++ Wl [nc];
Else
++ Overflow;
Nc = 0;
}
Else if (state = OUT)
{
State = IN;
Nc = 1;
}
Else
++ Nc;
For (I = 1; I <MAXWORD; ++ I)
Printf ("the number of words with length: % d is: % d: \ n", I, wl [I]);
Return 0;
}
Main ()
{
Wl ();
}
I am not good at writing. The article is for reference only. please correct me if you have any mistakes.
Have a nice day !!!
From the Aric hut