good algorithms come with practice and reading good code/books?

V

vlsidesign

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
 
A

August Karlstrom

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.

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
 
B

Barry Schwarz

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
 
N

newsman654

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.

My time is somewhat limited...
You are not alone.

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?
 
S

santosh

(e-mail address removed) wrote:
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.
 
R

Richard Heathfield

(e-mail address removed) said:

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.
 
N

newsman654

Richard Heathfield said:
(e-mail address removed) 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.
 
V

vlsidesign

August said:
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.
 
R

Richard Heathfield

(e-mail address removed) said:
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. :)
 
K

Keith Thompson

Richard Heathfield said:
(e-mail address removed) 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.
 
C

CBFalconer

.... snip ...

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.

Sedgewick is good, I don't know about Mastering Algorithms, but
anything by Schildt is fundamentally wrong and will give you evil
habits. It is generally known as BullSchildt around here. You
might want to get the ISO standard as the ultimate reference.
Search for N869 and/or N1124. A well formatted text version
suitable for quoting and easy searching with less is available,
bzip2 compressed, at:

<http://cbfalconer.home.att.net/download/>
 
R

Richard Heathfield

Keith Thompson said:
Richard Heathfield said:
(e-mail address removed) said: [...]
"The C Programming Language", 2nd edition, by Kernighan and Ritchie, is
an excellent reference.

It's probably a better tutorial than a reference.

That's probably a matter of taste. :)
"C: A Reference Manual", 5th edition, by Harbison and Steele, is an
excellent reference.

I have both (well, okay, 4th edition of H&S), but I invariably look stuff up
in K&R. Having said that, it may simply be because K&R guesses what I'm
looking for, and tends to fall open at the appropriate page, whereas H&S is
rather more aloof and makes me look stuff up in the index.
 
A

aegis

vlsidesign said:
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.

You might try your hand at functional programming. You should
realize this, if anything else, that C is not a very expressive
language.
Give that some thought while you learn a language like Scheme or
Haskell.
 
J

jacob navia

aegis a écrit :
You might try your hand at functional programming. You should
realize this, if anything else, that C is not a very expressive
language.
Give that some thought while you learn a language like Scheme or
Haskell.

Can you please give ma an example of commercial or
public domain software that is written in Haskell or in
Scheme?

I mean a substantial software system like a word processor
or a spreadsheet, a network application, a mail reader,
something like that.

Thanks
 
A

aegis

jacob said:
aegis a écrit :

Can you please give ma an example of commercial or
public domain software that is written in Haskell or in
Scheme?

I mean a substantial software system like a word processor
or a spreadsheet, a network application, a mail reader,
something like that.

DrScheme is mostly written in scheme.
 
J

jacob navia

aegis a écrit :
DrScheme is mostly written in scheme.

I meant APPLICATION software.

An application that does something, for instance
a spreadsheet, a word processor, whatever.
 
J

James Daughtry

jacob said:
I meant APPLICATION software.

An application that does something, for instance
a spreadsheet, a word processor, whatever.

Last I checked, development tools counted as application software.
Since you're applying unknown and unnecessary restrictions to prove
your point, perhaps you could define what you mean by "whatever" in
your list of acceptable applications.
 
N

Nelu

jacob said:
aegis a écrit :

I meant APPLICATION software.

An application that does something, for instance
a spreadsheet, a word processor, whatever.

- Sawfish (window manager)
- Emacs (real-time text editor) <- GNUS (mail client) <- emms <-
erc and so on. (Emacs and all the software written on top of it
with elisp make for a very substantial software system that's
well beyond any of you requirements :) ).
- AutoCAD uses lisp modules.
 
S

Spiros Bousbouras

Nelu said:
- Sawfish (window manager)
- Emacs (real-time text editor) <- GNUS (mail client) <- emms <-
erc and so on. (Emacs and all the software written on top of it
with elisp make for a very substantial software system that's
well beyond any of you requirements :) ).

Isn't elisp a different dialect of Lisp from scheme ?
 
J

jacob navia

Spiros Bousbouras a écrit :
Isn't elisp a different dialect of Lisp from scheme ?

yes, but it is the same "family".
Emacs itself is written in....

YES!!!!
YOU GUESSED IT!!!

But they have a small little "extensions" language (like
MatchCad), and many others where lisp shines.

I am NOT against lisp (as I am not "against" any
computer language, but in the real world there is
very little space apparently for this languages.

Scripting languages like perl/ruby/python, are
another stuff.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top