How to create, fill, and print a 2D array at runtime in VB.NET

1 Answer

0 votes
Imports System

Module Program

    Sub Main()
        Dim rows As Integer = 3
        Dim cols As Integer = 5

        ' Create and fill the array with random numbers
        Dim array As Integer(,) = CreateRandom2DArray(rows, cols)

        ' Print the array
        Print2DArray(array)
    End Sub

    ' ---------------------------------------------------------
    ' Creates a 2D array and fills it with random integers
    ' ---------------------------------------------------------
    Function CreateRandom2DArray(rows As Integer, cols As Integer) As Integer(,)
        ' Creates a 2D array
        Dim arr(rows - 1, cols - 1) As Integer
        Dim rnd As New Random()

        For i As Integer = 0 To rows - 1
            For j As Integer = 0 To cols - 1
                arr(i, j) = rnd.Next(1, 100) ' random 1–99
            Next
        Next

        Return arr
    End Function

    ' ---------------------------------------------------------
    ' Prints a 2D array in matrix form
    ' ---------------------------------------------------------
    Sub Print2DArray(arr As Integer(,))
        Console.WriteLine("2D array:")

        Dim rows As Integer = arr.GetLength(0)
        Dim cols As Integer = arr.GetLength(1)

        For i As Integer = 0 To rows - 1
            For j As Integer = 0 To cols - 1
                Console.Write(arr(i, j) & " ")
            Next
            Console.WriteLine()
        Next
    End Sub

End Module



' run:
'
' 2D array:
' 78 56 21 78 27 
' 43 87 65 45 5 
' 56 94 1 14 74 
' 

 



answered 1 day ago by avibootz
...