# Thread: Help with K&R Book Exercise

1. ## Help with K&R Book Exercise

Hi! I am learning C with the K&R book.
I have a problem with exercise 1.13 from page 24 it says
"Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging"
I 'm not sure if i understand what it wants (my native language is not English)
For example if a i write "Hello to all!" the program should print something like
1 **** (Hello)
2 ** (to)
3 **** (all!)
is this right? if so any hints?

Much thanks,
Cheers!

2. Yes, that looks about right.

What portion of this are you struggling with. Whilst this may not count as homework per se, me giving the answer directly would not be the right solution.

--
Mats

3. First all, thanks for the quick answer!

The problem i have is how to store the number of letters every word have. I can make an array to hold int's with the number of letters every word have and then do a for ..i am doing something like this..which is far from good

Code:
```int c, i, j, count, word_number = 0, word[SIZE];

while ((c = getchar()) != '1') {
if (c != ' ' && c != '\t' && c != '\n') {
++count;
}
else {
word[word_number] = count;
count = 0;
++word_number;
}

}
for (i = 0; i < word_number; ++i) {
printf("%d: ", i+1);
for (j = 0; j < word[i]; ++j) {
printf("*");
}
printf("\n");
}```
PS_ Ignore that 1 in the while condition, is because right now i am in windows..and Crt+Z don't works like in Linux.

4. Originally Posted by Alejandrito
PS_ Ignore that 1 in the while condition, is because right now i am in windows..and Crt+Z don't works like in Linux.
And why do you think so?

Code:
```#include <stdio.h>
int main(int argc, char *argv[])
{
int c = getchar();
if(c == EOF)
puts("EOF detected");
else
printf("Char found - %c", c);
return 0;
}```
I press Ctrl+z,Enter
Output
Code:
```^Z
EOF detected```

5. Originally Posted by vart
And why do you think so?

Code:
```#include <stdio.h>
int main(int argc, char *argv[])
{
int c = getchar();
if(c == EOF)
puts("EOF detected");
else
printf("Char found - %c", c);
return 0;
}```
I press Ctrl+z,Enter
Output
Code:
```^Z
EOF detected```
In linux, i don't need to press enter...
Back to my question i did it.
Code:
```#include <stdio.h>

#define SIZE 100

main()
{
int c, i, j, count = 0, word_number = 0, word[SIZE];

while ((c = getchar()) != EOF) {
if (c != ' ' && c != '\t' && c != '\n') {
++count;
}
else {
word[word_number] = count;
count = 0;
++word_number;
}

}

for (i = 0; i < word_number; ++i) {
printf("%d: ", i+1);
for (j = 0; j < word[i]; ++j) {
printf("*");
}
printf("\n");
}
}```
Cheers!

6. better make it
int main(void)

and add return 0; at the end

to be more standard

Popular pages Recent additions