Hey,

I am trying to create the sum of my values contained in MyArray variable simultaneously while assigning the values in the same loop. Afterwards, I want to find the average of the numbers after the loop finishes.

Problem: When I compute the numbers, I keep getting the same sum and average for whatever number I put in. How do I fix this problem?

Also, do you see any other errors in my code?

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click



        Try

            Dim Num As Integer = Convert.ToInt32(txtNumber.Text)
            Dim MyArray As Integer()
            Dim Sum As Integer
            Dim Average As Double


            MyArray = New Integer(200) {}

            For I = 0 To MyArray.GetUpperBound(0)

                MyArray(I) = I * 2

            Next

            

            For I = 0 To MyArray.GetUpperBound(0)

                Sum = Sum + MyArray(I)

            Next


            Average = Sum / MyArray.GetUpperBound(0)


            If Num > 199 Then
                MessageBox.Show("Please enter a number less than 200")
                txtNumber.Clear()
            Else

                MessageBox.Show("The Sum of Array Numbers is" & Sum & "and the Average is" & Average)
            End If



        Catch formatExceptionParameter As FormatException

            If txtNumber.Text = String.Empty Then

                MessageBox.Show("Please enter a number less than 200.")

            Else

                MessageBox.Show("Invalid character. Please type in a number less than 200.", "Invalid Number Format", _
                                MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        Catch OtherEx As Exception

            MessageBox.Show("There was a technical error, please email customer service for further assistance", "Unknown Error", _
                            MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try


    End Sub

I think it is suppose to be

MyArray(I) = I + 10

because I need it to be 10+ more than the integer.

You mention you get the same sum and average no matter which number you put in. Which line of code are you referring to when you say "for whatever number I put in".

Secondly, the following line

Average = Sum / MyArray.GetUpperBound(0)

should be

Average = Sum / (MyArray.GetUpperBound(0) + 1)

The upperBound function returns the largest index, which is one less of the number of items in the array.

This article has been dead for over six months. Start a new discussion instead.