For Loop Step -1 - vb.net

I want to know why this loop doesn't show anything in VB.NET.
I think this code will create an infinite loop. But it doesn't show anything.
Dim i as Integer
For i = 1 to 3 Step - 1
MessageBox.Show(i)
Next
Is that loop different with this code (in java/c#) ?
for(int i = 1;i <= 3;i--)
{
// print i
}

http://msdn.microsoft.com/en-us/library/5z06z1kb.aspx
With a negative step size the loop only executes if counter >= end. So in this case with i = 1, that is less than the ending value so the loop doesn't execute at all.

It doesn't show anything because you are running the counter backwards without reversing the start and end conditions.
Think of the loop like this:
Dim counter As Int32 = 1
Do
If counter <= 1 Then
Exit Do
End If
Console.WriteLine("The counter is at " & counter)
counter +=1
Loop
Obviously this won't work properly.
You need to reverse the start and end conditions:
For counter = 3 To 1 Step -1
Console.WriteLine("counter: " & counter)
Next

For i = 1 to 3 Step - 1
It won't create an infinite loop. The loop will simply be skipped, because you can't get from 1 to 3 with a step value of -1.
Is that loop different with this code (in java/c#) ?
This loop will also end immediately, because the initial value (i = 1) meets the exit condition (i <= 3).

Related

Reset index cycle for-next

Good morning,
I have a problem with the for-next loop. At the second iteration of the cycle, the exit from the cycle occurs even if the exit condition on variable j is not respected. I would have solved the problem with the goTo statement. However I am wondering why index reset does not work in this case.
Thank you.
For j = LBound(AttivitaTemp) To UBound(AttivitaTemp)
If confronta(AttivitaTemp(j), AttivitaFinali) = "#N/D" Then
activityTemp = AttivitaTemp(j)
rigaTemp = confronta(activityTemp, Attivita)
SuccessioniTemp = estrai_riga(MatriceElenchiSuccessioni, rigaTemp)
SuccessioniTemp = cancella_vuoti_vettore(SuccessioniTemp)
ESsuccessioni = EF(rigaTemp)
For k = LBound(SuccessioniTemp) To UBound(SuccessioniTemp)
rigaTemp = confronta(SuccessioniTemp(k), Attivita)
ES(rigaTemp) = Application.WorksheetFunction.Max(ES(rigaTemp), ESsuccessioni)
EF(rigaTemp) = ES(rigaTemp) + Durate(rigaTemp)
Next
VettoreSuccessioniTemp = unisci_vettori(VettoreSuccessioniTemp, SuccessioniTemp)
If j = UBound(AttivitaTemp) Then
AttivitaTemp = VettoreSuccessioniTemp
ReDim VettoreSuccessioniTemp(0)
j = LBound(AttivitaTemp) - 1
'GoTo ricomincia_ciclo_j
End If
End If
Next
Observing the variable j at the second iteration it results j = 0, with the next it goes to j = 1 but the for loop is not re-executed, although UBound (AttivitaTemp) is equal to 1.
In other words, why does this simple cycle work instead, which conceptually does the same thing?
For x = 0 To 2
If x = 2 Then
x = -1
End If
Next
I solved it by myself: the problem is that even if it is possible to reset the iterator, it is not possible to update the conditions of the for loop (the values of "from" and "to" remain "frozen" even if during the loop they are changed).

Visual Basic dividing

I'm on visual basic and I'm reading through some piece of code my teacher wrote, he had this chunck of code:
Private Sub btnDividing_Click(sender As Object, e As EventArgs) Handles btnDividing.Click
Dim number As Integer = InputBox("Divide number by 2:")
Dim result As Integer = 0
Do While (number <> 0)
result += 1
number = number - 2
Loop
MsgBox("The result is: " & result, MsgBoxStyle.Exclamation)
End Sub
So my teacher typed the result += 1 and number = number -2 I didn't really understand that part so i tried simplifying it by changing it to:
Dim number As Integer = InputBox("Divide number by 2:")
Dim result As Integer = 0
Do While (number <> 0)
result = number / 2
Loop
MsgBox("The result is: " & result, MsgBoxStyle.Exclamation)
End Sub
but it keeps freezing after I click "OK"
Any suggestions?
It freezes because you made it an infinite loop:
Do While (number <> 0)
result = number / 2
Loop
The loop checks the value of number, but your modified code in the loop never modifies the value of number. So if the condition is true the first time it's checked, it will always be true. The original code modified the value:
Do While (number <> 0)
result += 1
number = number - 2
Loop
Since number is decremented by 2 with each iteration of the loop, it will eventually (assuming it's even) be equal to 0, making the loop condition false and the loop will end.
Basically, a loop needs to in some way modify the values being checked in the condition (or have some other control statement to exit the loop) or the loop will infinitely run.

skip over a value in a loop and then continue to loop?

I need to be able to run a loop starting at 0, have it identify a certain value (in this case piecenumblack) and then skip that value, and then continue the loop until it hits 11. I'm really unsure what type of loop to use and I've had no success with a Do, While, or For loop.
Dim piecenumblack As Integer
For i = 0 To piecenumblack
Next
For i = 11 To piecenumblack Step -1
Next
You could add an If to the inside of the loop:
Dim piecenumblack As Integer
piecenumblack = 3
For i = 0 To 11
If i <> piecenumblack then
'Do Code
End If
Next
This would then skip doing any code when i = 3 then continue on with 4,5,6..11.

VBA Override Error 6 Overflow (Create Infinite Loop)?

I want an infinite loop in VBA (I have done this in Java and C++ before). I keep getting "Overflow" with the VBCritical red circle X.
Here is my code. The Error <>0 is supposed to recognize the overflow and ignore it to let the macro continue looping infinitely, but I still get the overflow VBCritical MsgBox.
I want to print the numbers out in column A. This part works right now: it prints "2".
Here is my code:
Sub InfiniteLoop()
Dim counter As Integer
counter = 1
Do While counter > 0
counter = counter + 1
Loop
If Error <> 0 Then
Do While counter > 0
counter = counter + 1
Cells(counter, "A").Value = counter
Loop
End If
End Sub
For a loop that will run from 0..32767 repeatedly (the max an integer can hold)
Do While True
counter = (counter + 1) Mod 32768
...
Loop
If you dim counter as a Long the maximum will be 2147483647.
Could you not just do this? and not increment counter at all?
Sub InfiniteLoop()
Dim counter As Integer
counter = 1
Do While counter > 0
Loop
End Sub

Exit a while loop in VBS/VBA

Is there a method of exiting/breaking a while in VBS/VBA?
Following code won't work as intended:
num = 0
while (num < 10)
if (status = "Fail") then
exit while
end if
num = num+1
wend
VBScript's While loops don't support early exit. Use the Do loop for that:
num = 0
do while (num < 10)
if (status = "Fail") then exit do
num = num + 1
loop
what about changing the while loop to a do while loop
and exit using
Exit Do
While Loop is an obsolete structure, I would recommend you to replace "While loop" to "Do While..loop", and you will able to use Exit clause.
check = 0
Do while not rs.EOF
if rs("reg_code") = rcode then
check = 1
Response.Write ("Found")
Exit do
else
rs.MoveNext
end if
Loop
if check = 0 then
Response.Write "Not Found"
end if}
Incredibly old question, but bearing in mind that the OP said he does not want to use Do While and that none of the other solutions really work... Here's something that does exactly the same as a Exit Loop:
This never runs anything if the status is already at "Fail"...
While (i < 20 And Not bShouldStop)
If (Status = "Fail") Then
bShouldStop = True
Else
i = i + 1
'
' Do Something
'
End If
Wend
Whereas this one always processes something first (and increment the loop variable) before deciding whether it should loop once more or not.
While (i < 20 And Not bShouldStop)
i = i + 1
'
' Do Something
'
If (Status = "Fail") Then
bShouldStop = True
End If
Wend
Ultimately, if the variable Status is being modified inside the While (and assuming you don't need i outside the while, it makes no difference really, but just wanted to present multiple options...
I know this is old as dirt but it ranked pretty high in google.
The problem with the solution maddy implemented (in response to rahul) to maintain the use of a While...Wend loop has some drawbacks
In the example given
num = 0
While num < 10
If status = "Fail" Then
num = 10
End If
num = num + 1
Wend
After status = "Fail" num will actually equal 11. The loop didn't end on the fail condition, it ends on the next test. All of the code after the check still processed and your counter is not what you might have expected it to be.
Now depending on what you are all doing in your loop it may not matter, but then again if your code looked something more like:
num = 0
While num < 10
If folder = "System32" Then
num = 10
End If
RecursiveDeleteFunction folder
num = num + 1
Wend
Using Do While or Do Until allows you to stop execution of the loop using Exit Do instead of using trickery with your loop condition to maintain the While ... Wend syntax. I would recommend using that instead.
While many have mentioned Do While...Loop, there are no examples showing the While is not necessary:
count = 0
Do
count = count + 1
wscript.echo count
If (count > 9) Then
Exit Do
End If
'...Some other logic that can be ended early...
wscript.sleep(1000)
Loop
If you already have the variable to compare against and it makes sense to complete the loop, Do While... is great. However, if you're doing something a little more granular, like the WScript.Sleep above that delays the script can be avoided.
Use Do...Loop with Until keyword
num=0
Do Until //certain_condition_to_break_loop
num=num+1
Loop
This loop will continue to execute, Until the condition becomes true
While...Wend is the old syntax and does not provide feature to break loop! Prefer do while loops