How to iterate an array from the middle outward (stepping left and right alternately) in VB.NET

1 Answer

0 votes
Imports System

Module MiddleOut

    Sub Main()

        ' Array to iterate
        Dim arr() As Integer = {0, 1, 2, 3, 4, 5, 6, 7}
        Dim n As Integer = arr.Length

        ' Middle index for even-sized arrays
        Dim mid As Integer = n \ 2

        ' Left starts before the middle, right starts at the middle
        Dim left As Integer = mid - 1
        Dim right As Integer = mid

        ' Iterate outward from the middle
        While left >= 0 Or right < n

            If right < n Then
                Console.Write(arr(right) & " ")
                right += 1
            End If

            If left >= 0 Then
                Console.Write(arr(left) & " ")
                left -= 1
            End If

        End While

    End Sub

End Module




' run:
'
' 4 3 5 2 6 1 7 0 
'

 



answered Jun 29 by avibootz

Related questions

...