Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What is wrong with this for/next loop
#6
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.  Wink
Reply


Messages In This Thread
RE: What is wrong with this for/next loop - by SMcNeill - 04-15-2025, 01:41 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Exiting sub while inside a loop PhilOfPerth 5 525 12-05-2025, 09:40 AM
Last Post: PhilOfPerth
  Do Loop, Sleep and Mouse Button Dimster 5 599 09-06-2025, 12:57 PM
Last Post: Dimster
  Using modulo to loop through lists fistfullofnails 3 723 09-03-2025, 11:50 PM
Last Post: fistfullofnails
  Simple Addition gone wrong Dimster 13 1,469 08-22-2025, 09:00 PM
Last Post: Pete
  Either I'm doing MID$( wrong or it has a bug TDarcos 4 813 04-13-2025, 11:14 PM
Last Post: TDarcos

Forum Jump:


Users browsing this thread: 1 Guest(s)