#include <stdio.h>
#include <stdbool.h>
#define N 3
// Function to check if the matrix is a magic square
bool isMagicSquare(int matrix[][N], int size) {
int sumDiagonal1 = 0, sumDiagonal2 = 0;
// Calculate the sum of the primary diagonal
for (int i = 0; i < size; i++) {
sumDiagonal1 += matrix[i][i];
}
// Calculate the sum of the secondary diagonal
for (int i = 0; i < size; i++) {
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) {
return false;
}
// Check sums of each row and column
for (int i = 0; i < size; i++) {
int sumRow = 0, sumCol = 0;
for (int j = 0; j < size; j++) {
sumRow += matrix[i][j]; // Sum of the current row
sumCol += matrix[j][i]; // Sum of the current column
}
// If any row or column sum is not equal to the diagonal sum, it's not a magic square
if (sumRow != sumDiagonal1 || sumCol != sumDiagonal1) {
return false;
}
}
// If all checks pass, it's a magic square
return true;
}
int main() {
int matrix[N][N] = { {8, 3, 4}, {1, 5, 9}, {6, 7, 2} };
// Check if the matrix is a magic square
if (isMagicSquare(matrix, N)) {
printf("The given matrix is a magic square.\n");
} else {
printf("The given matrix is NOT a magic square.\n");
}
return 0;
}
/*
run:
The given matrix is a magic square.
*/