A magic square is an arrangement of numbers (usually integers) in a square grid, where the numbers in each row, and in each column, and the numbers in the forward and backward main diagonals, all add up to the same number.
Write a program to find whether a given matrix is a magic square or not.
Sample Input:
2
4 5
5 4
Sample Output:
no
Sample Input:
3
4 9 2
3 5 7
8 1 6
Sample Output:
yes
Program Code:
#include<stdio.h>
int main()
{
int size;
scanf("%d",&size);
int matrix[size][size];
int row, column = 0;
int sum, sum1, sum2;
int flag = 0;
for (row = 0; row < size; row++)
{
for (column = 0; column < size; column++)
scanf("%d", &matrix[row][column]);
}
//For diagonal elements
sum = 0;
for (row = 0; row < size; row++)
{
for (column = 0; column < size; column++)
{
if (row == column)
sum = sum + matrix[row][column];
}
}
//For Rows
for (row = 0; row < size; row++)
{
sum1 = 0;
for (column = 0; column < size; column++)
{
sum1 = sum1 + matrix[row][column];
}
if (sum == sum1)
flag = 1;
else
{
flag = 0;
break;
}
}
//For Columns
for (row = 0; row < size; row++)
{
sum2 = 0;
for (column = 0; column < size; column++)
{
sum2 = sum2 + matrix[column][row];
}
if (sum == sum2)
flag = 1;
else
{
flag = 0;
break;
}
}
if (flag == 1)
printf("\nyes");
else
printf("\nno");
return 0;
}
Post A Comment:
0 comments: