Reputation: 11
When program finished FOR statment, counter is greater then end number. As long i know, at the end(after next) counter has same value then end value (for counter=1 to end). Can someone please explain.
Dim all_lines = 5
Dim line As Integer
Label1.Text = ""
For line = 1 To all_lines
Label1.Text += line & "/" & all_lines & Chr(13)
Next
Label1.Text += line & "/" & all_lines & Chr(13)
Result:
1/5
2/5
3/5
4/5
5/5
6/5
Upvotes: 0
Views: 257
Reputation: 54417
The loop counter is basically incremented at the Next
statement and then tested against the limits at the For
statement. If it's not greater than the upper limit then the loop is entered, otherwise it exits. It happens this way because you can specify a Step
of greater than 1 and the loop doesn't want to calculate ahead of time whether the current loop counter value plus the Step
value will exceed the upper limit. It just waits until the loop counter actually contains that value and tests it then.
It's important to realise that the For
loop is really just syntactic sugar and the compiled code is basically a Do
loop. If you wrote your code as a Do
loop then it would be more obvious why your loop counter exceeds the upper limit:
Dim all_lines = 5
Dim line As Integer
Label1.Text = ""
line = 1
Do While line <= all_lines
Label1.Text += line & "/" & all_lines & Chr(13)
line += 1
Loop
Label1.Text += line & "/" & all_lines & Chr(13)
You really shouldn't be using the loop counter outside the loop in the vast majority of cases anyway. That means that you shouldn't be declaring it outside the loop, i.e. do this:
For i As Integer = 0 To upperBound
rather than this:
Dim i As Integer
For i = 0 To upperBound
In any case where you actually need to use the loop counter outside the loop, it would be because the loop is doing a search and you should therefore have an Exit For
statement inside your loop that will prevent the loop counter being incremented further.
Upvotes: 1
Reputation: 180
It's the very last line outside the loop:
Label1.Text += line & "/" & all_lines & Chr(13)
Remove this.
Code should be:
Dim all_lines = 5
Dim line As Integer
Label1.Text = ""
For line = 1 To all_lines
Label1.Text += line & "/" & all_lines & Chr(13)
Next
Having the extra line is causing your issue. "Line" will equal 6 in order to get exit out of the loop, and you're doing an operation on it - outside the loop:
Label1.Text += line & "/" & all_lines & Chr(13)
so yes, you will get the results you're experiencing. Just remove the last line of code.
Upvotes: 0