Home »
VB.Net »
VB.Net Programs
VB.Net program to find the first repeated element in the one-dimensional array
By Nidhi Last Updated : November 14, 2024
Find the first repeated element in an array
Here, we will create an array of integers and then read elements from the user. After that, we will find the first repeated item in the array.
Program/Source Code:
The source code to find the first repeated element in the one-dimensional array is given below. The given program is compiled and executed successfully.
VB.Net code to find the first repeated element in an array
'VB.Net program to find the first repeated element
'in a one-dimensional array.
Module Module1
Sub Main()
Dim arr As Integer() = New Integer(6) {}
Dim index As Integer = 0
Dim item As Integer = 0
Console.WriteLine("Enter array elements: ")
For i = 0 To 5 Step 1
Console.Write("Element[{0}]: ", i)
arr(i) = Integer.Parse(Console.ReadLine())
Next
index = -1
'check first repeated element
For i = 0 To 5 Step 1
For j = i + 1 To 5 Step 1
If (arr(i) = arr(j)) Then
item = arr(j)
index = j
GoTo OUT
End If
Next
Next
OUT:
If (index <> -1) Then
Console.WriteLine("{0} repeated @ {1} index", item, index)
Else
Console.WriteLine("There is no repeated element")
End If
End Sub
End Module
Output
Enter array elements:
Element[0]: 10
Element[1]: 12
Element[2]: 12
Element[3]: 14
Element[4]: 15
Element[5]: 16
12 repeated @ 2 index
Press any key to continue . . .
Explanation
In the above program, we created a module Module1 that contains a function Main(). In the Main(), we created an array arr of six elements and we also created more variables item, index which are initialized with 0.
Console.WriteLine("Enter array elements: ")
For i = 0 To 5 Step 1
Console.Write("Element[{0}]: ", i)
arr(i) = Integer.Parse(Console.ReadLine())
Next
In the above code, we read the values of array elements from the user.
index = -1
'check first repeated element
For i = 0 To 5 Step 1
For j = i + 1 To 5 Step 1
If (arr(i) = arr(j)) Then
item = arr(j)
index = j
GoTo OUT
End If
Next
Next
OUT:
If (index <> -1) Then
Console.WriteLine("{0} repeated @ {1} index", item, index)
Else
Console.WriteLine("There is no repeated element")
End If
In the above code, we find the first repeated item in the array, if an item is found in the array then we print the index of the repeated item otherwise "There is no repeated element" message will be print on the console screen.
VB.Net Array Programs »