Click here to Skip to main content
13,050,450 members (78,316 online)
Rate this:
Please Sign up or sign in to vote.
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

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

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
            ' A correct max value is assigned to incorrect student name
            MsgBox(students(i).name & " " & max)
    End Sub
Posted 30-Mar-13 15:32pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

This line makes no sense and would not compile in "normal" language:
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:
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. :-)


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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.170713.1 | Last Updated 5 Apr 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100