04-15-2025, 01:41 PM
Lots of people have answered this, but let me go ahead and add my two cents worth on WHY it works this way.
FOR i = 1 TO 5
NEXT
PRINT i
For the above, it seems reasonable to assume that i *could* be 5. We're running a loop and counting from 1 to 5, so *WHY* is the value 6 after that loop?
That's easily explained with a second set of code:
FOR i = 1 TO 10 STEP 2
NEXT
PRINT i
Now, with the above, I can never *be* to 10. It counts by 2, starting at 1, so I will be:
1 -- first loop
3 -- second loop
5 -- third loop
7 -- fourth loop
9 -- fifth loop
11 -- greater than 10, so EXIT loop
As you can see, I can *never* be 10 as we're counting odd numbers... So how would this loop ever terminate IF it had to match the target number exactly?
Obviously, it couldn't.
Instead, the loop runs until the variable EXCEEDS the target value. In this case, it'd be 11. We set the FOR loop to run from 1 TO 10, and we count by 2, so 11 would be when it first exceeds that value.
In the FOR i = 1 TO 5, it works the same way. The process starts counting at 1, adds 1 each loop, and only stops once it EXCEEDS 5.
1... start loop and add 1 each pass
2...add one
3...add one
4 ...add one
5 ...add one (5 still doesn't EXCEED 5, so we continue on)
6... Exceeds 5, so EXIT loop
And that's basically the *WHY* it behaves the way it does. A FOR loop starts at the first number, counts by the STEP, and repeats until it EXCEEDS the second number.
^ It's just that simple of a process.
FOR i = 1 TO 5
NEXT
PRINT i
For the above, it seems reasonable to assume that i *could* be 5. We're running a loop and counting from 1 to 5, so *WHY* is the value 6 after that loop?
That's easily explained with a second set of code:
FOR i = 1 TO 10 STEP 2
NEXT
PRINT i
Now, with the above, I can never *be* to 10. It counts by 2, starting at 1, so I will be:
1 -- first loop
3 -- second loop
5 -- third loop
7 -- fourth loop
9 -- fifth loop
11 -- greater than 10, so EXIT loop
As you can see, I can *never* be 10 as we're counting odd numbers... So how would this loop ever terminate IF it had to match the target number exactly?
Obviously, it couldn't.
Instead, the loop runs until the variable EXCEEDS the target value. In this case, it'd be 11. We set the FOR loop to run from 1 TO 10, and we count by 2, so 11 would be when it first exceeds that value.
In the FOR i = 1 TO 5, it works the same way. The process starts counting at 1, adds 1 each loop, and only stops once it EXCEEDS 5.
1... start loop and add 1 each pass
2...add one
3...add one
4 ...add one
5 ...add one (5 still doesn't EXCEED 5, so we continue on)
6... Exceeds 5, so EXIT loop
And that's basically the *WHY* it behaves the way it does. A FOR loop starts at the first number, counts by the STEP, and repeats until it EXCEEDS the second number.
^ It's just that simple of a process.

