Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to check whether a matrix is a magic square or not in VB.NET

1 Answer

0 votes
Imports System

Public Class MagicSquareChecker
    Public Shared Function IsMagicSquare(ByVal matrix As Integer(,)) As Boolean
        Dim size As Integer = matrix.GetLength(0)
        Dim sumDiagonal1 As Integer = 0, sumDiagonal2 As Integer = 0

        For i As Integer = 0 To size - 1
            sumDiagonal1 += matrix(i, i)
        Next

        For i As Integer = 0 To size - 1
            sumDiagonal2 += matrix(i, size - i - 1)
        Next

        If sumDiagonal1 <> sumDiagonal2 Then
            Return False
        End If

        For i As Integer = 0 To size - 1
            Dim sumRow As Integer = 0, sumCol As Integer = 0

            For j As Integer = 0 To size - 1
                sumRow += matrix(i, j)
                sumCol += matrix(j, i)
            Next

            If sumRow <> sumDiagonal1 OrElse sumCol <> sumDiagonal1 Then
                Return False
            End If
        Next

        Return True
    End Function

    Public Shared Sub Main()
        Dim matrix As Integer(,) = {
        {8, 3, 4},
        {1, 5, 9},
        {6, 7, 2}}

        If IsMagicSquare(matrix) Then
            Console.WriteLine("The given matrix is a magic square.")
        Else
            Console.WriteLine("The given matrix is NOT a magic square.")
        End If
    End Sub
End Class


' run:
'
' The given matrix is a magic square.
'

 



answered Sep 30, 2025 by avibootz
...