0000
0000

Reputation: 677

Outer Nested loop returns value twice?

I'm writing an application that basically runs through a 2 dimensional array and multiplies the values of each item in the array by 2, for some reason the outer loop does this twice each time it reiterates. Why is this happening?

Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
    ' multiplies each array element by 2 and then displays the results in a list box

    Dim intInventory(,) As Integer = {{45, 67}, {2, 4}, {50, 7}, {9, 8}}

    For indexOuter As Integer = 0 To intInventory.GetUpperBound(0)
        intInventory(indexOuter, 0) *= 2
        lstInventory.Items.Add(intInventory(indexOuter, 0))

        For indexInner As Integer = 0 To intInventory.GetUpperBound(1)
            intInventory(indexOuter, indexInner) *= 2
            lstInventory.Items.Add(intInventory(indexOuter, indexInner))
        Next
    Next

End Sub

Upvotes: 0

Views: 93

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103447

Don't do this:

    intInventory(indexOuter, 0) *= 2
    lstInventory.Items.Add(intInventory(indexOuter, 0))

Because it's covered by the first iteration (indexInner=0) of this:

    For indexInner As Integer = 0 To intInventory.GetUpperBound(1)
        intInventory(indexOuter, indexInner) *= 2
        lstInventory.Items.Add(intInventory(indexOuter, indexInner))

Upvotes: 2

Related Questions