Is there any way to use non-linear step in vb.net loop?

I would like to make the following c statement in vb.

for(int i = 2^20; i > 0; i/=2)
{
   printf("%d\n",i); 
}  

In vb it will look something like this:

For i As Integer = 2^32 to 0 Step /2
   Console.Out.Writeline("{0}", i)
Next

In particular, the variable where I am divided by 2, each iteration is not legal vb.

Is there a way to write this with a For statement, which is allowed?

+3
source share
2 answers

No, the FOR loop in VB is shorter, but less flexible.

And the obvious work is, of course, the While loop.

' untested
Dim i As Integer = 2^30  ' 2^32 will overflow
While i >= 0
   Console.Writeline("{0}", i)
   i = i Div 2
End While
+4
source

There are two typical approaches:

  • Derive a formula for converting a linear index (preferably an integer value) to any values ​​necessary for a loop, and then use such a formula.
  • "IEnumerable" , "For" "For Each"

- , ; , LINQ (- Enumerable.Range), .

+1

All Articles