![]() |
Code Critique
Hi, all. I don't so much have a problem. My code works (or at least, it does in all tests I've ran so far), but as I'm still working on some of the examples in K&R, I'm just looking for some comments. Criticisms especially. If I've done something dumb, I want to know about it. Any feedback is helpful :D.
Please note that I'm not using pointers, functions, or anything that has not been introduced yet at this time in the book... trying to play fair. :D Anywhoo... here's the assignment, from the K&R text. Quote:
:
/* K&RThanks, Phil |
1) Declare your array to be of dimension MAXSIZE rather than MAXSIZE+1, and set loop conditions accordingly. For example, your first loop would be;
:
for (i = 0; i < MAXSIZE; ++i)2) Favour preincrement (eg ++arr[nc-1]) over postincrement (eg arr[nc-1]++) unless you need to use the previous value. 3) If the first character in your input is a space, then the logic will be (commented) :
nc = 0;4) Rather than testing against various whitespace characters, try the function isspace() which is in <ctype.h> 5) Compute the max value in your array like this; :
highest = arr[i];6) Better yet, eliminate the computation of max and simply sort the array (but retain duplicate values). Then the values will contain values in order that you want to print them, and you simply need to count the number of times a value is in sequence to get the value for your histogram. This will be more efficient than what you're doing (printing highest, searching the whole array for that value, decrementing highest, and going over and over again). |
Quote:
:
while ((c = getchar()) != EOF) { Phil |
My third comment is about a real problem in your code; that problem is a showstopper. If your user inputs a space as the first character (or a '\n' or a '\t' ....) the program yields undefined behaviour. This is because of a basic flaw in your program logic. Read the comments in the code snippet I gave to see why.
The point of my 4th comment is to use isspace() from <ctype.h>. That is a minor improvement, which has nothing to do with addressing the preceding problem of undefined behaviour. |
Quote:
At any rate, I added an additional test to the second if statement (see comments), only entering the statement if nc is between 0 and MAXSIZE. When I get home I'm going to work on this some more. I do appreciate the help, though! :-) :
|
A couple more comments
1) If you use a test case that contains two or more spaces in sequence, the histogram will not be correct. I'm guessing all your test cases only have one space between two words. 2) Something that works along the lines; :
++x;[code] :
if (some_condition) |
| All times are GMT -5. The time now is 12:41 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC