Click here to Skip to main content
15,892,517 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
What is the best way to get the max value from the array and match it to other elements of the array?

Data example in array:

Lisa 76
John 82
Kate 59
Peter 74

I can get the max value from the array but it doesn't assign the correct name of the student to it.

I have following array and simplified structure:

Dim students(3) As student

VB
Structure student
        Dim name As String
        Dim Average As Double
End Structure

VB
Private Sub btnfindMax_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnfindMax.Click
        Dim i As Integer
        Dim max As Double

        max = students(i).Average

        For i = 0 To Len(students(i).Average) - 1
            If students(i).Average > max Then
                max = students(i).Average
            End If
        Next
           
            ' A correct max value is assigned to incorrect student name
            MsgBox(students(i).name & " " & max)

    End Sub
Posted

H!, Buddy

You want to max value with its student name, right ?

You store you data in array or any other tables or dataset.

You can find easily max value with that name.

Here no need to take variable Average.

First you need to find that Index of array in which stored max value, you also called that GetPostionsOfMaxValue

When you find index of max value, on that you get stored name and value of that particular index.
I hope you will understand, if any question so fill free comment on my answer.

Happy Coding Buddy.
:)
 
Share this answer
 
This line makes no sense and would not compile in "normal" language:
VB
max = students(i).Average


First of all i is not assigned; second of all, you should not declare it, and finally, getting any element of the array for initial value of max won't make a correct algorithm. Instead do this:
VB
max = double.NegativeInfinity


This special value will correctly compare using '<' operator (and other comparison operators) with any other double value except NaN and will serve as a correct initial value for maximum. Indeed, there won't be any number less then double.NegativeInfinity.

If you also need to use the name (or some other member of the student structure), you need to search not just for maximum, but also remember the index of the maximum element. If you think just a bit, you will easily modify the code the get it. :-)

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900