sangeen
sangeen

Reputation: 304

How do you find greatest number among 5 with vb.net?

This is code for finding maximum in 3 but i want the code for finding maximum amoung 5:

Dim a, b, c As Integer

a = InputBox("enter 1st no.") 
b = InputBox("enter 2nd no.") 
c = InputBox("enter 3rd no.")

If a > b Then 
    If a > c Then 
        MsgBox("A is Greater") 
    Else 
        MsgBox("C is greater") 
    End If 
Else 
    If b > c Then 
        MsgBox("B is Greater") 
    Else 
        MsgBox("C is Greater")
    End If 
End If 

Upvotes: 5

Views: 45930

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112447

As David suggested, keep your values in a list. That's easier than using individual variables and can be extended to as many values as requested (up to millions of values).

If you need to keep individual variables for some reason, do this:

Dim max As Integer = a
Dim name As String = "A"
If b > max Then
    max = b
    name = "B"
End If
If c > max Then
    max = c
    name = "C"
End If
If d > max Then
    max = d
    name = "D"
End If
' ...  extend to as many variables as you need.
MsgBox(name & " is greater")

Upvotes: 4

David
David

Reputation: 218887

Put the values into an array and use the Max function on IEnumerable:

'Requires Linq for Max() function extension
Imports System.Linq
'This is needed for List
Imports System.Collections.Generic

' Create a list of Long values. 
Dim longs As New List(Of Long)(New Long() _
                                   {4294967296L, 466855135L, 81125L})

' Get the maximum value in the list. 
Dim max As Long = longs.Max()

' Display the result.
MsgBox("The largest number is " & max)

' This code produces the following output: 
' 
' The largest number is 4294967296

Upvotes: 17

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

A simple solution for you,

Dim xMaxNo As Integer
Dim xTemp As Integer

For i as integer = 1 To 5
   xTemp =  InputBox("enter No: " & i)
   xMaxNo = if(xTemp > xMaxNo, xTemp, xMaxNo)
Next

MsgBox("The Highest Number is " & xMaxNo)

Upvotes: 2

Related Questions