Lo Shu Magic Square The Lo Shu Magic Square is a grid with 3 rows and 3 columns
ID: 3595937 • Letter: L
Question
Lo Shu Magic Square The Lo Shu Magic Square is a grid with 3 rows and 3 columns . The Lo Shu Magic Square has the following properties:
• The grid contains the numbers 1 through 9 exactly.
• The sum of each row, each column, and each diagonal all add up to the same number.
* In a program you can simulate a magic square using a two-dimensional array.
* Write a function that accepts a two-dimensional array as an argument, and determines whether the array is a Lo Shu Magic Square.
* Test the method in a program.
note: it is 3 * 3
Explanation / Answer
For testing we are using 2 arrays 3*3:
int arr1[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int arr2[3][3]={{4,9,2},{3,5,7},{8,1,6}};
*************************************************************************************************
#include <stdio.h>
#include <stdlib.h>
int isLoShuMagicSquare(int arr[3][3]){
int d1 = arr[0][0] + arr[1][1] + arr[2][2];
int d2 = arr[0][2] + arr[1][1] + arr[2][0];
int r1 = arr[0][0] + arr[0][1] + arr[0][2];
int r2 = arr[1][0] + arr[1][1] + arr[1][2];
int r3 = arr[2][0] + arr[2][1] + arr[2][2];
int c1 = arr[0][0] + arr[1][0] + arr[2][0];
int c2 = arr[0][1] + arr[1][1] + arr[2][1];
int c3 = arr[0][2] + arr[1][2] + arr[2][2];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(arr[i][j]<1 || arr[i][j]>9)
return -1;
}
}
if(d1==d2 && d2==r1 && r1==r2 && r2==r3 && r3==c1 && c1==c2 && c2==c3)
return 1;
else
return -1;
}
int main()
{
int arr1[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int result = isLoShuMagicSquare(arr1);
if(result == 1)
printf("The array is Lo Shu Magic Square ");
else
printf("The array is not Lo Shu Magic Square ");
int arr2[3][3]={{4,9,2},{3,5,7},{8,1,6}};
result = isLoShuMagicSquare(arr2);
if(result == 1)
printf("The array is Lo Shu Magic Square ");
else
printf("The array is not Lo Shu Magic Square ");
return 0;
}
*************************************************************************************************
Sample input output:
The array is not Lo Shu Magic Square
The array is Lo Shu Magic Square
**************************************************************************************************
I hope this helps.
If you find my answer useful kindly rate the answer.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.