C# - Find if a matrix is a magic square.
C# - Find if a matrix is a magic square. The sum of elements in each row, each column and the diagonals should be equal. It is defined only for a square matrix.
CODE
using System;
namespace SampleNS
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("The magic square is defined for only square matrix.");
Console.Write("Enter the size of the magic square matrix: ");
int size = Convert.ToInt32(Console.ReadLine());
int[,] matrix = new int[size, size];
Console.Write("Enter the elements in the matrix...\n");
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
Console.Write("[{0}],[{1}] : ", i, j);
matrix[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
bool isMagicSquare = true;
//Calculate the sum of the prime diagonal
int primeDiagonalSum = 0;
for (int i = 0; i < size; i++)
{
primeDiagonalSum += matrix[i, i];
}
//Calculate the sum of the secondary diagonal
int secondaryDiagonalSum = 0;
for (int i = 0; i < size; i++)
{
secondaryDiagonalSum = secondaryDiagonalSum + matrix[i, size-1-i];
}
//Keep primeDiagonalSum as the base to check all the other sums
if (primeDiagonalSum == secondaryDiagonalSum)
{
for (int i = 0; i < size; i++)
{
int rowSum = 0;
int colSum = 0;
for (int j = 0; j < size; j++)
{
//Calculate the sum of rows
rowSum += matrix[i, j];
//Calculate the sum of cols
colSum += matrix[j, i];
}
if (rowSum != primeDiagonalSum || colSum != primeDiagonalSum)
{
isMagicSquare = false;
break;
}
}
}
else
isMagicSquare = false;
if (isMagicSquare)
Console.WriteLine("The given matrix is a magic square.");
else
Console.WriteLine("The given matrix is not a magic square.");
Console.ReadKey();
}
}
}
Comments
Post a Comment