Wednesday, June 8, 2011

Return Maximum Number in an array

I was asked to write a function to return the maximum number in a given array once in a job interview when I have little programming knowledge. I didn't make the move there but after I studied a bit, I found it is actually a very easy task. There are more than one way of doing this, I'll just illustrate two here:

Solution 1:

    Private Function GetMaxNumber() As Integer
        Dim ages() As Integer = {12, 53, 14, 26, 35, 24, 39, 45}
        'set the age of the first element for comparison
        Dim oldest As Integer = ages(0)

        'now loop through all the ages in the array
        For i As Integer = 0 To UBound(ages) - 1
            'check if the current age is greater than the highest age
            'that has been found so far
            If oldest < ages(i) Then
                'store the value of the element in the array
                oldest = ages(i)
            End If
        Next
        Return oldest
    End Function

Solution 2:


    Private Function GetMax() As Integer
        Dim nums() As Integer = {12, 53, 14, 26, 35, 24, 39, 45}
        Dim largest = (From num In nums Select num).Max

        Return largest
    End Function

Using LINQ in Visual studio 2008 you can tell it is much easier to do this