1
    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!

Matthias
  • 35
  • 4

2 Answers2

1

Why is the value of num not 5 when I specify to stop at 5?

To be precise, you specify that 5 is the last value to be processed (that is, loop body still runs when num is 5). At the end of an iteration, counter (num) is decremented and next iteration begins. num is now zero (less than 5) and loop exits because its stop condition is now satisfied. That's how you get that output.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • So the For loop will only stop when num goes below the number 5? Meaning it is not measuring the number against less than or equal to, it's simply just less than? – Matthias Jun 01 '17 at 19:23
  • @Matthias: it appears so. What does documentation say? – Sergio Tulentsev Jun 01 '17 at 19:24
  • "The counting repeats until Variable equals or exceeds the final value End." Quoted from https://social.technet.microsoft.com/wiki/contents/articles/16388.the-developers-reference-guide-to-small-basic-2-overview-of-small-basic-programming.aspx – Matthias Jun 01 '17 at 19:40
  • @Matthias: interesting. This contradicts the evidence. Are you sure that you indeed get 5 as the last value from the loop? – Sergio Tulentsev Jun 01 '17 at 19:42
1

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)

Gabriel
  • 1,922
  • 2
  • 19
  • 37
  • Ah! So the computer processes the post-operator as if it's appended to the end of the body. Thank you for your help @Gabriel – Matthias Jun 01 '17 at 20:19
  • This is a truism about For loops in any language. All values inside the loop will be valid and within the range. The value of the control is guaranteed to be outside of the range once the loop is complete. – codingCat Sep 01 '17 at 19:16