SkyVar
SkyVar

Reputation: 351

How to compare elements of an array

I'm trying to create a for loop to cycle through an array and perform a basic switch with a temporary variable to cycle out the highest number. I also need to print what position that element was in the array. This is what I have so far.

Dim highest As Decimal = gasArray(0)
Dim j As Integer = 1

For a As Integer = 0 To 11 Step 1
            If gasArray(a) < gasArray(a + 1) Then
                highest = gasArray(a + 1)
                a = j
            End If

        Next


        avgPriceLbl.Text = "$" & highest & " in month " & Array.FindIndex(j)

Upvotes: 0

Views: 518

Answers (2)

Derek Tomes
Derek Tomes

Reputation: 4007

Ok, you're new at this, hopefully the comments will make sense...

' create some dummy data
Dim gasArray() As Decimal = New Decimal() {1, 7, 23, 11, 57, 0}

Dim highest As Decimal
Dim index As Integer

' it's better to ask an array what the bounds are 
For a As Integer = gasArray.GetLowerBound(0) To gasArray.GetUpperBound(0) Step 1
    If highest < gasArray(a) Then
        highest = gasArray(a)
        index = a
    End If
Next

' this is a prettier way to create strings
avgPriceLbl.Text As String = String.Format("${0} in month {1}", highest, index)

Upvotes: 1

user2784234
user2784234

Reputation: 451

What you need is the following:

 j = 0
 highest = gasArray(j)
 For a As Integer = 1 To 11 Step 1
      If highest < gasArray(a) Then
            highest = gasArray(a)
            j = a
        End If

    Next

Upvotes: 1

Related Questions