teach-ict.com logo

THE education site for computer science and ICT

3. Logic errors cont.

Loop is off by one

This is a very common programming mistake - the code loops around one less than intended.

                 Line 30:            COUNT = 3
                 Line 31:            FOR i = 1, i < COUNT
                 Line 32:                 print i
                 Line 33:            NEXT i

The intention is to print out three values of i, namely 1,2,3. Can you see why it prints out 1,2 but not 3?

The problem is with i < COUNT, because the FOR loop ends when i becomes 3 and does not print out the last i. To fix it the compare has to be i <= COUNT i.e less than OR equal to COUNT. This is the corrected code

                 Line 30:            COUNT = 3
                 Line 31:            FOR i = 1, i <= COUNT
                 Line 32:                 print i
                 Line 33:            NEXT i
the kernel

Array indexes

It's very common in programming to have the first position within an array or list called the "0th index", rather than the "1st index". This can lead to some odd results if the programmer forgets where their indexes start.

Let's write some broken pseudocode to print out the first value of an array

                 Line 30:            MyArray = [5,6,7,8]
                 Line 31:            PRINT MyArray[1]

This prints "6" instead of "5"!

The correct code to print out the first value would be:

                 Line 30:            MyArray = [5,6,7,8]
                 Line 31:            PRINT MyArray[0]

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: What are some examples of logic errors in programming?