How to find the indexes of the first and last occurrences of an element in array in VB.NET

1 Answer

0 votes
Imports System

Public Class Program
    Public Shared Sub findFirstAndLastIndex(ByVal array As Integer(), ByVal element As Integer)
        Dim first As Integer = -1, last As Integer = -1
        Dim size As Integer = array.Length

        For i As Integer = 0 To size - 1
            If array(i) <> element Then
                Continue For
            End If

            If first = -1 Then
                first = i
            End If

            last = i
        Next

        If first <> -1 Then
            Console.WriteLine("First Occurrence = " & first)
            Console.WriteLine("Last Occurrence = " & last)
        Else
            Console.Write("Not Found")
        End If
    End Sub

    Public Shared Sub Main(ByVal args As String())
        Dim array As Integer() = New Integer() {3, 2, 4, 7, 3, 0, 9, 8, 7, 7, 12, 18}
        Dim element As Integer = 7
	
        findFirstAndLastIndex(array, element)
    End Sub
End Class



' run:
'
' First Occurrence = 3
' Last Occurrence = 9
'

 



answered Dec 7, 2023 by avibootz
...