In writing this program you must use constants For example, square[1][2] isn\'t
ID: 3665328 • Letter: I
Question
In writing this program you must use constants
For example, square[1][2] isn't as clear as square[MIDDLE_ROW][RIGHT_COL].
Write a program to test whether a square is a 3x3 magic square. A magic square is a grid with 3 rows and 3 columns, like the figure below. A magic square has the following properties:
the grid contains only the numbers 1 through 9
the sum of each row, each column, and each diagonal all add up to the same number
Notes:
I have provided the start to the program, which creates and displays the square.
You will complete the missing method: isMagic.
You should try different test values to make sure your program works properly.
Your program only has to work for 3x3 squares. It does not need to work more generally for other-sized magic squares.
If you are going to hard-code in positions to take advantage of this, for full credit, use constants instead of numbers to improve readability.
For example, square[1][2] isn't as clear as square[MIDDLE_ROW][RIGHT_COL].
Explanation / Answer
#include<stdio.h>
#include<conio.h>
int main() {
int size = 3; /* size of the matrix */
int matrixone[3][3];
int row, column = 0;
int sumdiagnol, sumrow,sumcolumn;
int flag = 0;
printf(" Enter the given matrix : ");
for (row = 0; row < size; row++) {
for (column = 0; column < size; column++)
scanf("%d", &matrixone[row][column]);
}
printf("Entered matrix is : ");
for (row = 0; row < size; row++) {
printf(" ");
for (column = 0; column < size; column++) {
printf(" %d", matrixone[row][column]);
}
}
// Checking For the diagonal elements
sumdiagnol = 0;
for (row = 0; row < size; row++) {
for (column = 0; column < size; column++) {
if (row == column)
sumdiagnol = sumdiagnol + matrixone[row][column];
}
}
// checking for Rows and calculating sum
for (row = 0; row < size; row++) {
sumrow = 0;
for (column = 0; column < size; column++) {
sumrow = sumrow + matrixone[row][column];
}
if (sumdiagnol == sumrow)
flag = 1;
else {
flag = 0;
break;
}
}
// Checking For the columns and calculating sum
for (row = 0; row < size; row++) {
sumcolumn = 0;
for (column = 0; column < size; column++) {
sumcolumn = sumcolumn + matrixone[column][row];
}
if (sumdiagnol == sumcolumn)
flag = 1;
else {
flag = 0;
break;
}
}
if (flag == 1)
printf(" It is a magic square");
else
printf("It is not a magic square");
return 0;
}