This chapter introduces arrays and how to use them to count the number of characters in each of the words of an input file. Pretty simple and easy ideas. The problems are challenging though.
Exercise 1.13
This exercise wants you to make a histogram of the number of letters in each word. I used the state variable again to determine whether or not I was in a word. If I came across a space and the state was IN, then I knew I had just finished a word and could increment the proper number. The part that took awhile to figure out was to include a category for all words with more than ten letters in them. Once I got the program up and running that assumed all words were ten letters or less, which wasn’t hard, I essentially had to add if-else statements everywhere to check and see if the letter count was higher than ten. More tedious than anything, and I missed a couple, meaning I had to go back and do lots of debugging.
int c, i, j, state, count;
int ndigit[MAXLENGTH + 1]; //track words with 10+ letters separately
count = 0;
for (i=0; i
ndigit[i] = 0;
state = OUT;
while ((c = getchar()) != 'q')
if (c == ' ' || c == '\n' || c == '\t') {
if (state == IN) {
if (count <= MAXLENGTH) {
++ndigit[count-1];
}
else {
++ndigit[MAXLENGTH];
}
count = 0;
state = OUT;
}
}//if
else {
state = IN;
++count;
}//else
if (state == IN) {//necessary if there is no space between the final letter and the 'q'
if (count <= MAXLENGTH) {
++ndigit[count-1];
}
else
++ndigit[MAXLENGTH];
}//if
for (i = 0; i < MAXLENGTH + 1; ++i) {
printf("%d-letter words: ",i+1);
for(j = 0; j < ndigit[i]; j++) {
printf("X");
}
printf("\n");
}//for
Exercise 1-14
This program was pretty simple. Since any character I type in on my American keyboard is going to be an ASCII character of some type, I made an array of 256 spaces, just incremented each space when its ASCII code was used, and then only printed out the histogram for characters that showed up in the sentence. Once we get outside of ASCII this wouldn't work, but for basic letters, numbers, and punctuation, it was fine.
int c, i, j, state, count;
int ndigit[MAXLENGTH]; //track words with 10+ letters separately
count = j = 0;
for (i=0; i
ndigit[i] = 0;
while((c = getchar()) != 'q') {
++ndigit[c];
}//while
printf("\n\n\n");
for(i = 0; i < MAXLENGTH; i++) {
if(ndigit[i] > 0) {
printf("ASCII %d: ", i);
for(j = 0; j < ndigit[i]; j++)
printf("X");
printf(" (%d)", ndigit[i]);
printf("\n");
}//if
}//for