Programming Fundamentals/Arrays/VB.NET

From Wikiversity
Jump to navigation Jump to search

arrays.vb[edit | edit source]

' This program uses arrays to display temperature conversion tables 
' and temperature as an array subscript to find a given conversion.
'
' References:
'     https://www.mathsisfun.com/temperature-conversion.html
'     https://en.wikibooks.org/wiki/Visual_Basic_.NET

Imports System

Public Module Arrays
    Sub Main
        Dim C() As Double
        Dim F() As Double
        
        C = BuildC(100)
        F = BuildF(212)
        DisplayArray("C", C)
        DisplayArray("F", F)
        FindTemperature(C, F)
    End Sub

    Private Function BuildC(Size As Integer) As Double()
        Dim C() As Double
        Dim Index As Integer
        Dim Value As Double
        
        ReDim C(Size)
        For Index = 0 To Size
            Value = Index * 9 / 5 + 32
            C(Index) = Value
        Next
        
        Return C
    End Function

    Private Function BuildF(Size As Integer) As Double()
        Dim F() As Double
        Dim Index As Integer
        Dim Value As Double
        
        ReDim F(Size)
        For Index = 0 To Size
            Value = (Index - 32) * 5 / 9
            F(Index) = Value
        Next
        
        Return F
    End Function

    Private Sub DisplayArray(Name As String, Array() As Double)
        Dim Index As Integer
        
        For Index = 0 To Array.Length - 1
            Console.WriteLine(Name & "[" & Index & "] = " & Array(Index))
        Next
    End Sub

    Private Sub FindTemperature(C() As Double, F() As Double)
        Dim Temp As Integer
        Dim Size As Integer
        
        Size = Minimum(C.Length, F.Length)
        Do
            Console.WriteLine("Enter a temperature between 0 and " & (Size - 1))
            Temp = Convert.ToInt32(Console.ReadLine())
        Loop While Temp < 0 Or Temp > Size - 1
        Console.WriteLine(Temp & "° Celsius is " & C(Temp) & "° Fahrenheit")
        Console.WriteLine(Temp & "° Fahrenheit is " & F(Temp) & "° Celsius")
    End Sub

    Private Function Minimum(Value1 As Integer, Value2 As Integer) As Integer
        Dim Result As Integer
        
        If Value1 < Value2 Then
            Result = Value1
        Else
            Result = Value2
        End If
        
        Return Result
    End Function
End Module

Try It[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own VB.NET compiler / interpreter / IDE.

See Also[edit | edit source]