Programming blunders

The word “blunder” is one of those nice words  which means is a spectacularly bad decision or action. I have seen it used in “The Elements of Programming Style”, and feel that some programming faults are probably more aptly termed blunders. Things that you didn’t really mean to happen, they just did, and they usually aren’t all that hard to fix.

Let’s consider first a program to calculate the harmonic series:


To implement this equation would require an upper bound n, and a loop of some sort. Consider this code in C:

double harmonic;
int k;
for (k=1; k<=n; k=k+1)
    harmonic = harmonic + 1.0/k;

This simple program should work, if properly coded, but there is a small problem with this code. Can you see it? Look at the value of the variable harmonic inside the loop. It seems to be a successive sum of the various components of the harmonic series, up until n. But what happens when you run this program with the n=4. You get a result, which doesn’t exactly look right. Now try doing the math on paper, and compare answers.

If you now look through the code, you will notice that the variable harmonic has never been given an initial value. This is not a problem for most compilers, who will just assign harmonic a garbage number. This will be the initial value onto which the values of the harmonic series are added.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.