Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   good algorithms come with practice and reading good code/books? (http://www.velocityreviews.com/forums/t445699-good-algorithms-come-with-practice-and-reading-good-code-books.html)

vlsidesign 12-30-2006 09:53 AM

good algorithms come with practice and reading good code/books?
 
I am a newbie and going through "The C programming language" by
Kernighan & Richie on my own time (I'm not a programmer but I want to
learn because it can save me time in my normal job, and it is kind of
fun). As I go through the book, I seek to do all the exercises because
they are very useful, and good, but it seems like I am just stumbling
through somewhat. In particular, I don't really know how to think about
"catching errors", or how my thought process should be. Right now, I
just try to come up with an algorithm by following the book and
improvising. I'll then try to test my code by throwing different things
at it (for instance, different types of input in different forms) and
see if it breaks, I then try to figure out why it broke and then patch
in the fix. My time is somewhat limited and I cannot at this time take
a C class at a junior college, but I was wondering if this is just part
of learning? Do I just need to continue reading various texts,
practicing, and studying code and I will acquire error checking and
more robust code over time? Any suggestions, hints, words of advice,
would be greatly appreciated. Thanks very much.

Here is my program by the way:

#include <stdio.h>

//program that counts the number of words and total chars
// but without whitespace, and newlines

// tracks going in/out of words for purpose of counting
#define IN 1 //inside a word
#define OUT 1 //outside a word

main ()
{
int c; //var that holds char read from stdin
int state; //flag for in/out of words
int nc; //counts chars per word
int tnc; //counts total chars minus any whitespace, and newlines
int nw; //total number of words

//initialize variables
c = 0;
low = 0;
state = 0;
nc = 0;
tnc = 0;
nw = 0;

//read char at a time until end of file (ctrl-d)
while ( (c = getchar()) != EOF ) {
if ( c == '\n' || c == '\t' || c == ' ') {
state = OUT;
if (nc > 0) ++nw;
nc = 0;
} else {
state = IN; //if you are not OUT then you are IN
++nc;
++tnc;
}
}//while
printf("Number of words %d .. Number of non-whitespace chars %d \n",
nw, tnc);
}//main


August Karlstrom 12-30-2006 03:48 PM

Re: good algorithms come with practice and reading good code/books?
 
vlsidesign skrev:
[...]
> Here is my program by the way:
>
> #include <stdio.h>
>
> //program that counts the number of words and total chars
> // but without whitespace, and newlines
>
> // tracks going in/out of words for purpose of counting
> #define IN 1 //inside a word
> #define OUT 1 //outside a word


You probably want the constants to have distinct values.

>
> main ()


Should be `int main(void)'.

> {
> int c; //var that holds char read from stdin
> int state; //flag for in/out of words


I would use a boolean variable `int insideword' or `bool insideword'
(after including stdbool.h) instead. It will make the program both
clearer and shorter.

Anyway, here is my version of the program:

#include <ctype.h>
#include <stdio.h>

int main(void)
{
int c, words = 0, chars = 0, insideword = 0;

c = getchar();
while (c != EOF) {
if (isspace(c)) {
if (insideword) { words++; }
insideword = 0;
} else {
chars++;
insideword = 1;
}
c = getchar();
}
if (insideword) { words++; }
printf("Found %d words and %d non-whitespace characters\n",
words, chars);
return 0;
}


August

Barry Schwarz 12-30-2006 04:58 PM

Re: good algorithms come with practice and reading good code/books?
 
On 30 Dec 2006 01:53:10 -0800, "vlsidesign" <fordgwf@gmail.com> wrote:

>I am a newbie and going through "The C programming language" by
>Kernighan & Richie on my own time (I'm not a programmer but I want to
>learn because it can save me time in my normal job, and it is kind of
>fun). As I go through the book, I seek to do all the exercises because
>they are very useful, and good, but it seems like I am just stumbling
>through somewhat. In particular, I don't really know how to think about
>"catching errors", or how my thought process should be. Right now, I
>just try to come up with an algorithm by following the book and
>improvising. I'll then try to test my code by throwing different things
>at it (for instance, different types of input in different forms) and
>see if it breaks, I then try to figure out why it broke and then patch
>in the fix. My time is somewhat limited and I cannot at this time take
>a C class at a junior college, but I was wondering if this is just part
>of learning? Do I just need to continue reading various texts,
>practicing, and studying code and I will acquire error checking and
>more robust code over time? Any suggestions, hints, words of advice,
>would be greatly appreciated. Thanks very much.
>
>Here is my program by the way:
>
>#include <stdio.h>
>
>//program that counts the number of words and total chars
>// but without whitespace, and newlines
>
>// tracks going in/out of words for purpose of counting
>#define IN 1 //inside a word
>#define OUT 1 //outside a word


I don't think you want both to be 1.

>
>main ()
>{
> int c; //var that holds char read from stdin
> int state; //flag for in/out of words
> int nc; //counts chars per word
> int tnc; //counts total chars minus any whitespace, and newlines
> int nw; //total number of words
>
> //initialize variables
> c = 0;
> low = 0;
> state = 0;
> nc = 0;
> tnc = 0;
> nw = 0;
>
> //read char at a time until end of file (ctrl-d)


It's only a comment but remove the parenthetical phrase. ctrl-d is
unix specific (other systems hare different conventions) and it is not
equivalent to end of file (but merely a method for signaling end of
file from a certain input device). If you had redirected your input
to a file using the "<" shell convention, ctrl-d would have no special
meaning.

> while ( (c = getchar()) != EOF ) {
> if ( c == '\n' || c == '\t' || c == ' ') {


You might find the isspace function useful here.

> state = OUT;


You never make use of the value in state. See next comment.

> if (nc > 0) ++nw;


What happens if the first two words are separated by three spaces?
(Hint: you should only increment nw when state is set to IN.)

> nc = 0;
> } else {
> state = IN; //if you are not OUT then you are IN


You should avoid // comments on usenet. A compiler invoked in C90
mode may not accept them. Equally importantly, if they wrap as a
result of message line length, they produce syntax errors. Both
problems have the effect of reducing the number of people who can (or
are willing) to help solve your problem.

> ++nc;
> ++tnc;
> }
> }//while
>printf("Number of words %d .. Number of non-whitespace chars %d \n",
>nw, tnc);
>}//main



Remove del for email

newsman654@sbcglobal.net 12-30-2006 07:05 PM

Re: good algorithms come with practice and reading good code/books?
 
vlsidesign <fordgwf@gmail.com> wrote:

<snip>
> Right now, I just try to come up with an algorithm by following the book and
> improvising. I'll then try to test my code by throwing different things
> at it (for instance, different types of input in different forms) and
> see if it breaks, I then try to figure out why it broke and then patch
> in the fix.

There is nothing wrong with that path of learning. Patience is a virtue.

<snip>
> My time is somewhat limited...

You are not alone.

<snip>
> Do I just need to continue reading various texts,
> practicing, and studying code and I will acquire error checking and
> more robust code over time? Any suggestions, hints, words of advice,
> would be greatly appreciated. Thanks very much.


Here's a little background from me.
I started programming in the early 80s, because I couldn't find what I was looking
for in terms of software. It wasn't much - it was BASIC just to get what I needed.

I began to realize that I rather enjoyed pondering better programming methods, and
enjoyed learning about logic, programming, and algorithms.

Years later in the 90s I wanted to start making programs for my Windows 3.1 OS computer
so I learned Visual Basic. I had not taken 1 single computer programming course - so I figured I was
behind most people I knew who worked with computers, which forced me to read many books!

Jump ahead many years later - I had to learn .NET for work, and fell in love with C# (which now- no longer like and use)
as opposed to Visual Basic. But I had to learn a bunch of new concepts, which appeared to have originated from
Java. So I learned Java.

While learning Java, I saw many concepts which were also borrowed from the past so I went on to
study C++.

Studying C++ I learned that it was created to add OOP(Object Oriented Programming) concepts to C,
so I went back and learned C. While I was learning C, I realized that I had come full circle, and
had gone back to the "basics", but with better methods of programming, because I had studied so many different
programmers, authors, algorithms, and have made many programs that I later reworked as I learned new concepts.

So having come full circle back to C (which is now, what, around 30+ years old?) I decided to take the plunge
and jump into linux. I have never had more fun with computers than I do now, making programs with C, scripting with BASH, administering my own linux servers, and further automating tasks I had previously done manually. I have learned to love the
open source concept - browse many projects on sourceforge.net to find what I'm looking for.

Wow! What a path!

Some of the most fun I've had learning C (and the most frustrating) was using the book called PROGRAMMING CHALLENGES ISBN-10: 0387001638 ISBN-13: 978-0387001630. Written by 2 academics, this book is a compilation of 100 exercises to practice programming. You then submit your code to automated judges online to see if it passes. Personally, my favorite part is just determining the methods with which to solve the problems.

I also suggest as a reference Herb Schildt's Complete Reference to C (check out herbschildt.com)

But the book that really opened my eyes to the art of programming and algorithms was Mastering Algorithms with C ISBN 10: 1-56592-453-3 ISBN 13: 9781565924536.

If you really want to study algorithms in more depth, allow me also to suggest Algorithms in C parts 1-5, by Robert Sedgewick.

I can tell you this,
I'm no expert, but I enjoy what I do, and study every day (when time allows).
But that's the other part of the fun...
Knowing I have a limited amount of time to spend studying what I enjoy,
makes it all the more worth it.

Take your time, have fun, share ideas, offer aid, and stay humble.

I can't think of a better way to have fun with a computer than progamming with C.

But above all else, have fun and enjoy your progress,

otherwise why do it at all?


santosh 12-30-2006 07:11 PM

Re: good algorithms come with practice and reading good code/books?
 
newsman...@sbcglobal.net wrote:
<snip>
> I also suggest as a reference Herb Schildt's Complete Reference to C (check out herbschildt.com)


That book is not considered accurate enough. Harbison & Steele's
reference may be better choice.


Richard Heathfield 12-30-2006 07:25 PM

Re: good algorithms come with practice and reading good code/books?
 
newsman654@sbcglobal.net said:

<snip>

> I also suggest as a reference Herb Schildt's Complete Reference to C


....which tells us all we need to know about the quality of your advice.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.

newsman654@sbcglobal.net 12-30-2006 07:48 PM

Re: good algorithms come with practice and reading good code/books?
 
Richard Heathfield <rjh@see.sig.invalid> wrote:
> newsman654@sbcglobal.net said:
>
> <snip>
>
> ...which tells us all we need to know about the quality of your advice.
>


All I really use that book for is a reference to the c library functions.

But you are correct, Herb Schildt's book should not be used for much else.

Let me correct myself and suggest to pick out a good reference to the functions in the C library.

I would suggest to exhaust what exists in the libraries and 'know' the functions, so the beginner isn't reworking
what's already there.

vlsidesign 12-30-2006 08:13 PM

Re: good algorithms come with practice and reading good code/books?
 
August Karlstrom wrote:
> Anyway, here is my version of the program:

Cool. Thanks for sharing it :)

> #include <ctype.h>
> #include <stdio.h>
>
> int main(void)
> {
> int c, words = 0, chars = 0, insideword = 0;
>
> c = getchar();
> while (c != EOF) {
> if (isspace(c)) {

Thanks I was unaware of isspace function.

> if (insideword) { words++; }
> insideword = 0;

I like the way you did it and yours works, my didn't. I was doing it
like this
if (nc > 0) ++nw;
nc = 0;
My version here did take care of multiple spaces in a row because nc
(number of characters in word) is only > 0 if it is the first
whitespace char (coming out of word, and nc is not set to 0 yet), but
it incorrectly incremented nw (new word) when first character of input
was a whitespace.

> } else {
> chars++;
> insideword = 1;
> }
> c = getchar();
> }
> if (insideword) { words++; }

This catches when the last char is nonwhitespace and then EOF. My
version I didn't catch this.

> printf("Found %d words and %d non-whitespace characters\n",
> words, chars);
> return 0;
> }
>
>
> August

Thanks again for sharing that.


Richard Heathfield 12-30-2006 08:32 PM

Re: good algorithms come with practice and reading good code/books?
 
newsman654@sbcglobal.net said:

> Richard Heathfield <rjh@see.sig.invalid> wrote:
>> newsman654@sbcglobal.net said:
>>
>> <snip>
>>
>> ...which tells us all we need to know about the quality of your advice.
>>

>
> All I really use that book for is a reference to the c library functions.


Nice spot of back-pedalling. :-)

Unfortunately, it's no good as a library reference either.

For example, it suggests in the gets() description that "it is your job to
make sure that the array pointed to by str is not overrun", hinting that
this job is actually possible (which it isn't). This wouldn't be so bad if
Schildt warned against using gets(), but of course he uses it freely
throughout the book.

For example, it claims in the getchar() description that "since EOF is a
valid integer value, you must use feof() to check for end-of-file when
working with binary files", which is complete nonsense.

For example, it claims that fwrite() and fread() return int, whereas in fact
they return size_t.

For example, it claims that fflush() clears the contents of the input buffer
if given an input stream's file pointer, whereas in fact the behaviour is
undefined.

For example, it suggests in the strncpy() description that "if the string
pointed to by str2 is longer than count characters, the resultant string
pointed to by str1 is not null terminated", whereas in fact this happens if
the source string is longer than or equal to count characters.

In the same description, it gives the following example:

---- begin quote ----
The following fragment copies at most 79 characters of str1 into str2,
thus ensuring that no array boundary overflow occurs.

char str1[128], str2[80];

gets(str1);
strncpy(str2, str1, 79);
---- end quote ----

In fact, it ensures no such thing, for two reasons. Firstly, the use of
gets() means that it cannot be ensured that no array boundary overflow has
occurred. Secondly, since str2's value is initially indeterminate, if the
input given to gets() is exactly 79 characters long (not including the
terminator), those 79 characters will be copied, but str2 will not be
null-terminated, and thus even a printf is likely to violate the bounds of
the array (I say "likely" because it's just possible that str2[79] will
happen to be a '\0'). Thus, array bounds overflow prevention is *not*
ensured.

For example... well, I found those half-dozen obviously flawed examples in
the first six functions I looked at. Heaven knows how many more such
obvious errors there are, and we haven't even started to consider the
*subtle* errors.

> But you are correct, Herb Schildt's book should not be used for much else.


s/for much else/except as a door-stop/

> Let me correct myself and suggest to pick out a good reference to the
> functions in the C library.


"The C Programming Language", 2nd edition, by Kernighan and Ritchie, is an
excellent reference.

> I would suggest to exhaust what exists in the libraries and 'know' the
> functions, so the beginner isn't reworking what's already there.


That, at least, is sound advice. :-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.

Keith Thompson 12-30-2006 10:29 PM

Re: good algorithms come with practice and reading good code/books?
 
Richard Heathfield <rjh@see.sig.invalid> writes:
> newsman654@sbcglobal.net said:

[...]
> "The C Programming Language", 2nd edition, by Kernighan and Ritchie, is an
> excellent reference.


It's probably a better tutorial than a reference.

"C: A Reference Manual", 5th edition, by Harbison and Steele, is an
excellent reference.

--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.


All times are GMT. The time now is 12:51 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.