Dim rnd As New Random()
Dim randArray(10) As Integer
For n As Integer = 5 To 10
randArray(n) = rnd.Next(1, 100)
Next
Array.Sort(randArray)
For n As Integer = 5 To 10
txtOutput.AppendText(randArray(n).ToString + Space(4))
Next
Dim num1 As Double = randArray(randArray.Length \ 2)
Dim num2 As Double= randArray((randArray.Length \ 2) - 1)
Dim median As Double = (num1 + num2) \ 2
lblMedian.Text = (median.ToString)
'' This value is 1 less then the number of values wanted, arrays are zero based
Dim numberOfValues As Integer = 9
Dim rnd As New Random()
'' This array had 11 elements in it, index is zero based
'' An index of 9 gives 10 elements 0 - 9
Dim randArray(numberOfValues - 1) As Integer
'' When I read this, "and the array's length is between 5 and 10.",
'' Now this For loop, "For n As Integer = 5 To 10", only uses the last 6
'' elements of the array leaving elements 0 - 4 empty. Is the statement looking to handle
'' any number of integers between 5 and 10 numbers. The modified For loop will always
'' load all elements of the array.
For n As Integer = 0 To (numberOfValues - 1)
randArray(n) = rnd.Next(1, 100)
Next
Array.Sort(randArray)
'' Modified For loop to match the number of elements in the array
'' Clear the text from last execution of this code
txtOutput.Clear()
lblMedian.Text = ""
For n As Integer = 0 To (numberOfValues - 1)
txtOutput.AppendText(randArray(n).ToString + Space(4))
Next
'' Using Integer Division
Dim num1 As Integer = (randArray.Length \ 2) - 1
Dim num2 As Integer = num1 + 1
Dim median As Double = 0.0
'' Test to see if the number of elements is even or odd
If numberOfValues Mod 2 = 0 Then
'' Is Even
median = (randArray(num1) + randArray(num2)) / 2
Else
'' Is Odd
median = randArray(num2)
End If
lblMedian.Text = (median.ToString)
If you are experiencing a similar issue, please ask a related question
Join the community of 500,000 technology professionals and ask your questions.
Connect with top rated Experts
21 Experts available now in Live!