How to print the boundary elements of a matrix in VB.NET

2 Answers

0 votes
Imports System

Module MatrixBoundary
    Sub PrintMatrixBoundaries(matrix As Integer(,), rows As Integer, cols As Integer)
        For i As Integer = 0 To rows - 1
            For j As Integer = 0 To cols - 1
                ' Check if the element is on the boundary
                If i = 0 OrElse j = 0 OrElse i = rows - 1 OrElse j = cols - 1 Then
                    Console.Write(matrix(i, j) & " ")
                End If
            Next
        Next
    End Sub

    Sub Main()
        Dim matrix As Integer(,) = {
            {1, 2, 3, 4, 5},
            {6, 7, 8, 9, 10},
            {11, 12, 13, 14, 15},
            {16, 17, 18, 19, 20}
        }

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

        PrintMatrixBoundaries(matrix, rows, cols)
    End Sub
End Module



' run:
' 
' 1 2 3 4 5 6 10 11 15 16 17 18 19 20 
'

 



answered Dec 15, 2025 by avibootz
0 votes
Imports System

Module MatrixBoundary
    Sub PrintMatrixBoundaries(matrix As Integer(,), rows As Integer, cols As Integer)
        ' Print first row
        For j As Integer = 0 To cols - 1
            Console.Write(matrix(0, j) & " ")
        Next

        ' Print last column
        For i As Integer = 1 To rows - 1
            Console.Write(matrix(i, cols - 1) & " ")
        Next

        ' Print last row in reverse
        For j As Integer = cols - 2 To 0 Step -1
            Console.Write(matrix(rows - 1, j) & " ")
        Next

        ' Print first column upwards
        For i As Integer = rows - 2 To 1 Step -1
            Console.Write(matrix(i, 0) & " ")
        Next
    End Sub

    Sub Main()
        Dim matrix As Integer(,) = {
            {1, 2, 3, 4, 5},
            {6, 7, 8, 9, 10},
            {11, 12, 13, 14, 15},
            {16, 17, 18, 19, 20}
        }

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

        PrintMatrixBoundaries(matrix, rows, cols)
    End Sub
End Module



' run:
' 
' 1 2 3 4 5 10 15 20 19 18 17 16 11 6 
'

 



answered Dec 15, 2025 by avibootz
...