[wplug] about basic programming

Bill Moran wmoran at potentialtech.com
Fri Mar 4 16:04:55 EST 2005


Tom Rhodes <trhodes at FreeBSD.org> wrote:

> On Fri, 4 Mar 2005 14:03:13 -0500
> John Harrold <jmh17 at pitt.edu> wrote:
> 
> > Sometime in March Juan Zuluaga assaulted the keyboard and produced:
> > 
> 
> [SNIP]: Discussion on books.
> 
> Perhaps someone with years of experiance in programming could
> tell me something.  In the following program snip-it:
> 
> #include <stdio.h>
> 
> #define lastnum 40
> 
> int main()
> {
> 
>   int num = 0;
> 
>   while ((num == 0) || (num < lastnum))
>     {
>       printf("Counting %d up\n", num);
>       num++;
>     }
>   return 0;
> }
> 
> num is only incremented to 39, one below 40.  Thus far I have
> always considered it was because we stop at the number before
> the one we define.  So I have always wrote as such.  Yet, I
> have not found an explination in either of my two C books.
> Am I missing or not properly enterpreting a paragraph/sentence
> in my books?
> 
> Yea, I'm sure everyone thinks I'm nuts now since I should know
> this, but, eh, whatever.  *hand in the air* You don't know me!
> :)

This is often called an "off by one" error ... it's a fairly common
mistake.

The reason it happens is because of how the while loop functions.
A while loop works like this:

while (condition) { commands }

Commands are executed as long as condition is true.  As soon as
condition is false, the while loop is done and execution continues
at the command after the while loop.  At the point at which num == 40,
num is no longer less than 40, thus the loop is never executed when
num == 40.  There are a lot of ways you could change this code to get
slightly different results ... for example, move the "num++" before
the printf and see how things change.  Can you see why?  The most
frequent way to handle this kind of loop is to check for "num <= lastnum",
which means that it will execute as long as num is less than or equal
to lastnum.

HTH.

-- 
Bill Moran
Potential Technologies
http://www.potentialtech.com


More information about the wplug mailing list