Search code examples
for-loopconsole-applicationbasicsmallbasic

Basic: Why is the result different than the value in this For loop?


    For num = 100 To 5 Step -5
        TextWindow.WriteLine(num)
    EndFor

The final value for this code that is displayed in the console is 5. However, when using the 'num' variable outside of the For loop, the value of 'num' results in 0. Why is the value of num not 5 when I specify to stop at 5? What is the computer logic that is happening here?

    For num = 100 To 5 Step -5
        TextWindow.WriteLine(num)
    EndFor
    TextWindow.WriteLine(num)

With the snippet above, the final value for 'num' in the console is displayed as 0.

Thank you all ahead of time for taking a moment to help me with this beginner issue!


Solution

  • This code

    For num = 100 To 5 Step -5
        ' Body
    EndFor
    

    Is the same as

    num = 100
    
    While num >= 5
        ' Body
    
        num = num - 5
    End While
    

    So the loop ends when num gets 0.

    (Sorry if there is some mistake in the code I provided, I wrote it by heart)