I am very new to programming in general, so please bear with my lack of knowledge.
I have spent a couple of hours now on exercise 1-13. I finally decided to look up the answer, which I found at this link https://github.com/ccpalettes/the-c-programming-language-second-edition-solutions/blob/master/Chapter1/Exercise%201-13/word_length.c .
Because I didn't want to copy it completely for the sake of learning, I tried to understand the code and then remake it. (This resulted in almost a complete copy, but I understand it better than I would have otherwise.)
This is what I have so far:
#include <stdio.h>
#define IN 1
#define OUT 0
#define LARGEST 10
main()
{
int c, state, l, i, j;
int length[LARGEST + 1];
for (i = 0; i <= LARGEST; ++i)
length[i] = 0;
state = OUT;
while ((c = getchar()) != EOF) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
if (state == OUT) {
l = 0;
state = IN;
}
++l;
}
else
if (state == IN) {
if (l <= LARGEST)
++length[l - 1];
//minus 1 because the nth term of an array is actually array[n-1]
else //if (l > LARGEST)
++length[LARGEST];
state = OUT;
}
if (c == EOF)
break;
}
for (i = 0; i <= LARGEST; ++i) {
if (i != LARGEST) //because array[10] refers to the 11th spot
printf("\t %2d |", i + 1); //plus one because 1st is array [0]
//this actually results in 1-10 because the 0-9 plus one makes the highest 10
else
printf("\t>%2d |", LARGEST);
for (j = 0; j < length[i]; ++j)
putchar('x');
putchar('\n');
}
return 0;
}
Please ignore my comments. They were meant for me, so that I could explain the program to myself.
I am having two issues that I just can't figure out, and they're driving me crazy:
The output always accounts for one word less than in the input, meaning "my name is not bob" results in:
... 2 |xx 3 |x 4 |x ...
Also, I don't understand what is going on at the end of the program. Specifically, I don't understand here why the variable
j
is being used:for (j = 0; j < length[i]; ++j) putchar('x');
Thanks so much for your help, and I'm sorry if this is too beginner for the community.