C Program to check if the entered matrix is magic square or not
Program
#include<stdio.h>
#define SIZE 3
void main()
{
int matrix[3][3];
int row, column;
int diagonal_sum, row_sum, col_sum;
int flag = 0;
printf("Enter matrix of order 3x3:\n");
for (row = 0; row < SIZE; row++)
{
for (column = 0; column < SIZE; column++)
scanf("%d", &matrix[row][column]);
}
printf("Entered matrix is:\n");
for (row = 0; row < SIZE; row++)
{
for (column = 0; column < SIZE; column++)
{
printf("%d\t", matrix[row][column]);
}
printf("\n");
}
diagonal_sum = 0;
for (row = 0; row < SIZE; row++)
{
for (column = 0; column < SIZE; column++)
{
if (row == column)
diagonal_sum = diagonal_sum + matrix[row][column];
}
}
for (row = 0; row < SIZE; row++)
{
row_sum = 0;
for (column = 0; column < SIZE; column++)
{
row_sum = row_sum + matrix[row][column];
}
if (diagonal_sum == row_sum)
flag = 1;
else
{
flag = 0;
break;
}
}
for (row = 0; row < SIZE; row++)
{
col_sum = 0;
for (column = 0; column < SIZE; column++)
{
col_sum = col_sum + matrix[column][row];
}
if (diagonal_sum == col_sum)
flag = 1;
else
{
flag = 0;
break;
}
}
if (flag == 1)
printf("Entered matrix is a magic square\n");
else
printf("Entered matrix is not a magic square\n");
}
Output 1
Enter matrix of order 3x3:
4
9
2
3
5
7
8
1
6
Entered matrix is:
4 9 2
3 5 7
8 1 6
Entered matrix is a magic square
Output 2
Enter matrix of order 3x3:
5
7
2
9
11
45
68
10
8
Entered matrix is:
5 7 2
9 11 45
68 10 8
Entered matrix is not a magic square