-1

When solving a question of Project Euler I ran into the following logical error related to when n is updated.

while(n<1000):
    #update n
    #do something with n
    #do stuff

vs

while(n<1000):
    #do something with n
    #do stuff
    #update n

In the first instance, I ended up performing an operation with n even though the condition of n<1000 is violated.

Does this logical error have a name? How common is this bug?

I tried to look for it, I did find things about pre-incrementing and post-incrementing a variable. Although that is close to the error, it isn't exactly what is happening here. I found a reference to this in a SO answer about for loop vs while loop in the part describing how for loops are more concise and direct when compared to while loops. Essentially with while loops we end up running code after a variable update which could be buried somewhere in the code.

Tejas Anil Shah
  • 1,421
  • 11
  • 20
  • 1
    the simple rule here is the while loop evaluates the condition then will run everything inside it. If you change n to be something that doesnt satisfy the while condition, the loop will finish the remaining code inside it as the expression of `n` is only evaluated at the end of the iteration and decides if we start the loop again – Chris Doyle Oct 24 '19 at 18:13
  • 1
    There's no logical error there, that's just how `while` works. – b_c Oct 24 '19 at 18:24

1 Answers1

1

This is not always a bug: it depends on the algorithm. In some cases, you know that the original value of n is legal (so you can enter the loop), but you want to update and use the new value in your processing. You need to match your code to your algorithm. Your second code block is the canonical for-equivalent, and is more common.

This falls under the general heading of "off by 1 error".

Prune
  • 76,765
  • 14
  • 60
  • 81