473,320 Members | 1,922 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

k&r2 exercise 1-13 review

Hi All,

I have done the horizontal version of exercise 1-13 and just wanted to
make sure that I had done it right as I was not fully sure what a
histogram was.

I also wanted to check to see if anyone had any suggestions on how to
make it better and if I had any bugs I was not aware of.

The output of the program is below. some of the * will probably wrap:

$ cat exercise_1-13.c | ./exercise_1-13

1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *
2 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * *
3 * * * * * * * * * * * * * * *
4 * * * * * * * * * * * * * *
5 * * * * * * * * * * *
6 * * * * * *
7 * * *
8 * * * *
9 * * * * *
10 * *
11 * *
12 * *
13 * * *
14 * *
15 * *
16 *

-------------------------
exercise_1-13.c
-------------------------

/* 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. */

#include <stdio.h>
#define MAX 22

main() {
int i, ii, number, space, c, nbr_array[MAX];
number = space = c = i = ii = 0;

for (i = 0; i < MAX; i++)
nbr_array[i] = 0;

while((c = getchar()) != EOF) {
if (space 0) {
if (c != ' ' && c != '\t') {
space = 0;
number = 1;
}
}
else {
if (c != ' ' && c != '\t' && c != '\n')
++number;
if (c == ' ' || c == '\t')
space = 1;
if (space 0 || c == '\n')
++nbr_array[number - 1];
}
}

for (i = 0; i < MAX; i++) {
if (nbr_array[i] 0) {
printf("\n%d", i + 1);
for (ii = 0; ii < nbr_array[i]; ii++) {
printf(" *");
}
}
}

printf("\n");
}
-------------------------------

Thanks for any input you may have.

Kind Regards,
Anthony Irwin
Mar 30 '07 #1
3 1766
In article <13*************@corp.supernews.com>,
Anthony Irwin <no****@nowhere.nomailwrote:
>Hi All,

I have done the horizontal version of exercise 1-13 and just wanted to
make sure that I had done it right as I was not fully sure what a
histogram was.

I also wanted to check to see if anyone had any suggestions on how to
make it better and if I had any bugs I was not aware of.
Overall it's pretty good, especially if you've only read as far as chapter 1.
The results aren't quite right though.
>
#include <stdio.h>
#define MAX 22

main() {
Most of us prefer the more verbose "int main(void)" these days.
int i, ii, number, space, c, nbr_array[MAX];
number = space = c = i = ii = 0;
"number" and "space" could have been more descriptively named, or commented.
Eventually I figured out that they represent "current_word_length" and
"currently_in_word".
for (i = 0; i < MAX; i++)
nbr_array[i] = 0;

while((c = getchar()) != EOF) {
if (space 0) {
That test (space 0) is kind of strange. "space" is never set to any value
other than 0 and 1. It's a natural boolean, so you could simply use
"if (space) {" instead.
if (c != ' ' && c != '\t') {
Here's the bug I referred to. Newline should also be considered a word
separator. If you run your program with an input that contains 2 lines with
just a few letters on each line, you'll see that it incorrectly counts the 2
lines as a single word.
space = 0;
number = 1;
}
}
else {
if (c != ' ' && c != '\t' && c != '\n')
Here you treated space, tab, and newline as equivalent...
++number;
if (c == ' ' || c == '\t')
Here you've omitted the newline again...
space = 1;
if (space 0 || c == '\n')
And then stuck the newline test as an afterthought? Be consistent: put all
three of the tests for ' ' and '\t' and '\n' together. There's no reason to
treat newline differently from the other two.
++nbr_array[number - 1];
What happens here if the input contains a word longer than MAX? The array
index will be too big and the program will no longer behave predictably. It
might crash or just print out bogus results. Before you get too far in your
studies, you should develop a habit of checking for invalid input. Make the
program print an error message when number MAX instead of doing the
increment, or make it increment a separate counter of "huge words" and print
that counter out as the last line of the histogram.
}
}

for (i = 0; i < MAX; i++) {
if (nbr_array[i] 0) {
printf("\n%d", i + 1);
Printing the newline at the beginning instead of the end is a weird choice,
but it still separates lines properly so it's not too bad. You just get an
extra blank line at the top.
for (ii = 0; ii < nbr_array[i]; ii++) {
printf(" *");
}
Right here, after the inner for loop, would be the most logical place to
print a newline after the row of stars.
}
}

printf("\n");
And if you did the \n after the inner loop, you wouldn't need this one at the
end.
>}
--
Alan Curry
pa****@world.std.com
Mar 30 '07 #2
Alan Curry wrote:
Overall it's pretty good, especially if you've only read as far as chapter 1.
The results aren't quite right though.
I am only in chapter 1 of k&r but I have looked at some other c books
before k&r.
>#include <stdio.h>
#define MAX 22

main() {

Most of us prefer the more verbose "int main(void)" these days.
Yes that is true but I am trying to stick with what k&r have in their
book for their exercises. they haven't even done return 0; yet in the
main function but I believe they cover that in the section on functions
a couple more pages in.
> int i, ii, number, space, c, nbr_array[MAX];
number = space = c = i = ii = 0;

"number" and "space" could have been more descriptively named, or commented.
Eventually I figured out that they represent "current_word_length" and
"currently_in_word".
Good point I guess it could be hard for other readers. I sort of had
space for if it is in a space and number for the number of characters in
the current word but it's not obvious to those that did not write the
code or to me later down the track.
> for (i = 0; i < MAX; i++)
nbr_array[i] = 0;

while((c = getchar()) != EOF) {
if (space 0) {

That test (space 0) is kind of strange. "space" is never set to any value
other than 0 and 1. It's a natural boolean, so you could simply use
"if (space) {" instead.
In C is any number 1 true or is only 1 true?

> ++nbr_array[number - 1];

What happens here if the input contains a word longer than MAX? The array
index will be too big and the program will no longer behave predictably. It
might crash or just print out bogus results. Before you get too far in your
studies, you should develop a habit of checking for invalid input. Make the
program print an error message when number MAX instead of doing the
increment, or make it increment a separate counter of "huge words" and print
that counter out as the last line of the histogram.
Yeah I totally didn't think about exceeding the array size. I now check
that number < MAX before adding the number to the array.
Thanks for the suggestions and spending the time to look at the code.

Kind Regards,
Anthony Irwin
Mar 31 '07 #3
On Mar 30, 6:04 pm, Anthony Irwin <nos...@nowhere.nomailwrote:
Alan Curry wrote:
[snip]
In C is any number 1 true or is only 1 true?
Any non-zero value is true and zero is false.
Mar 31 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Chris Readle | last post by:
Ok, I've just recently finished a beginning C class and now I'm working through K&R2 (alongside the C99 standard) to *really* learn C. So anyway, I'm working on an exercise in chapter one which...
16
by: Josh Zenker | last post by:
This is my attempt at exercise 1-10 in K&R2. The code looks sloppy to me. Is there a more elegant way to do this? #include <stdio.h> /* copies input to output, printing */ /* series of...
2
by: arnuld | last post by:
there is a solution on "clc-wiki" for exercise 1.17 of K&R2: http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_1:Exercise_17 i see this uses pointers whereas K&R2 have not discussed pointers...
8
by: arnuld | last post by:
i have created a solutions myself. it compiles without any trouble and runs but it prints some strange characters. i am not able to find where is the trouble. ...
4
by: arnuld | last post by:
as i said, i have restarted the book because i overlooked some material. i want to have some comments/views on this solution. it runs fine, BTW. ------------------ PROGRAMME -------------- /*...
16
by: arnuld | last post by:
i have created solution which compiles and runs without any error/ warning but it does not work. i am not able to understand why. i thought it is good to post my code here for correction before...
2
by: arnuld | last post by:
i was not even able to understand how should i proceed tow rite solution for this exercise: "Write a program to print a histogram of the frequencies of different characters in its input." ...
4
by: arnuld | last post by:
any suggestions for improvement: -------------- PROGRAMME ------------- /* K&R2: section 1.5.3 exercise 1-10 STATEMENT: write a programme to copy its input to output, replacing each TAB by...
16
by: arnuld | last post by:
i am not able to make it work. it compiles without any error but does not work: what i WANTED: 1.) 1st we will take the input in to an array. (calling "getline" in "main") 2.) we will print...
88
by: santosh | last post by:
Hello all, In K&R2 one exercise asks the reader to compute and print the limits for the basic integer types. This is trivial for unsigned types. But is it possible for signed types without...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.