Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What is wrong with this for/next loop
#4
Quote:This is how the FOR loop operates in BASIC
IMHO it seems how FOR loop operates...
when you exit from the loop the counter of loop will be max + 1 because until the counter is max it must run the loop!

Code: (Select All)

Rem this demo showes how FOR  works
Screen 0
While 1
    Cls , (Rnd * 6) + 1
    Locate 1, 1
    Print "Press 1 for Original FOR-NEXT "
    Print "Press 2 for GOTO version of FOR-NEXT"
    Print "Press 0 to quit program"
    a$ = Input$(1)
    If a$ = "0" Then
        End
    ElseIf a$ = "1" Then
        OriginalFORNEXT
    ElseIf a$ = "2" Then
        GOTODemoFORNEXT
    End If
    Color 31, 9: Print "Press a key for continue": Sleep: _KeyClear: Color 15, 0
Wend
End
Sub OriginalFORNEXT ()
    Dim counter As Integer
    counter = 0
    Print "Counter before FOR"; counter
    Print " Counter in the loop of FOR"
    For counter = 1 To 5 Step 1
        Print counter
    Next counter
    Print " Counter after loop FOR"; counter
End Sub
Sub GOTODemoFORNEXT ()
    Dim counter As Integer
    counter = 0
    Print "Counter before FOR loop"; counter
    Print "Counter in the loop of FOR"
    nextTest:
    counter = counter + 1 ' the STEP of loop FOR-NEXT is set to 1
    If counter <= 5 Then
        Print counter
        GoTo nextTest
    End If
    Print "Counter after loop FOR"; counter
End Sub

here a screenshot of output using VScode
[Image: FOR-loop-demo.jpg]

and here a example in C
compiled with g++


[Image: FOR-Loop-in-C.jpg]
Reply


Messages In This Thread
RE: What is wrong with this for/next loop - by TempodiBasic - 04-14-2025, 08:19 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 724 09-03-2025, 11:50 PM
Last Post: fistfullofnails
  Simple Addition gone wrong Dimster 13 1,474 08-22-2025, 09:00 PM
Last Post: Pete
  Either I'm doing MID$( wrong or it has a bug TDarcos 4 817 04-13-2025, 11:14 PM
Last Post: TDarcos

Forum Jump:


Users browsing this thread: 1 Guest(s)