How to check whether a matrix is a magic square or not in Pascal

1 Answer

0 votes
program MagicSquareChecker;

const
  N = 3;

type
  Matrix = array[1..N, 1..N] of Integer;

// Function to check if the matrix is a magic square
function IsMagicSquare(matrix: Matrix): Boolean;
var
  sumDiagonal1, sumDiagonal2: Integer;
  sumRow, sumCol: Integer;
  i, j, size: Integer;
begin
  sumDiagonal1 := 0;
  sumDiagonal2 := 0;
  
  size := (high(matrix) - low(matrix) + 1);

  // Calculate the sum of the primary diagonal
  for i := 1 to size do
    sumDiagonal1 := sumDiagonal1 + matrix[i, i];

  // Calculate the sum of the secondary diagonal
  for i := 1 to size do
    sumDiagonal2 := sumDiagonal2 + matrix[i, size - i + 1];

  // If the two diagonals don't have the same sum, it's not a magic square
  if sumDiagonal1 <> sumDiagonal2 then
  begin
    IsMagicSquare := False;
    Exit;
  end;

  // Check sums of each row and column
  for i := 1 to size do
  begin
    sumRow := 0;
    sumCol := 0;

    for j := 1 to size do
    begin
      sumRow := sumRow + matrix[i, j];  // Sum of the current row
      sumCol := sumCol + matrix[j, i];  // Sum of the current column
    end;

    // If any row or column sum is not equal to the diagonal sum, it's not a magic square
    if (sumRow <> sumDiagonal1) or (sumCol <> sumDiagonal1) then
    begin
      IsMagicSquare := False;
      Exit;
    end;
  end;

  // If all checks pass, it's a magic square
  IsMagicSquare := True;
end;

var
  m: Matrix;
begin
  // Initialize the matrix
  m[1,1] := 8; m[1,2] := 3; m[1,3] := 4;
  m[2,1] := 1; m[2,2] := 5; m[2,3] := 9;
  m[3,1] := 6; m[3,2] := 7; m[3,3] := 2;

  // Check if the matrix is a magic square
  if IsMagicSquare(m) then
    writeln('The given matrix is a magic square.')
  else
    writeln('The given matrix is NOT a magic square.')
end.



(*
run:

The given matrix is a magic square.

*)


  

 



answered Sep 30 by avibootz
edited Sep 30 by avibootz
...