C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
For-Each: Here we continually assign largest and smallest. You can call Max and Min with any two integers.
For Each, ForTip: If you use the integer you are assigning as an argument, the Integer variable will only increase (for Max) or decrease (for Min).
VB.NET program that uses Math.Max and Math.Min
Module Module1
Sub Main()
' Find largest and smallest elements in array.
Dim vals As Integer() = {1, 4, 100, -100, 200, 4, 6}
Dim largest As Integer = Integer.MinValue
Dim smallest As Integer = Integer.MaxValue
For Each element As Integer In vals
largest = Math.Max(largest, element)
smallest = Math.Min(smallest, element)
Next
Console.WriteLine(largest)
Console.WriteLine(smallest)
End Sub
End Module
Output
200
-100
However: If other statements must be used, the if-statement is better because fewer branches are required with one selection statement.