C Program to Check whether Matrix is Magic Square or Not ?
C Program to Check whether entered matrix is magic square or not ?
What is Magic Square :
- A magic square is a simple mathematical game developed during the 1500.
- Square is divided into equal number of rows and columns.
- Start filling each square with the number from 1 to num ( where num = No of Rows X No of Columns )
- You can only use a number once.
- Fill each square so that the sum of each row is the same as the sum of each column.
- In the example shown here, the sum of each row is 15, and the sum of each column is also 15.
- In this Example : The numbers from 1 through 9 is used only once. This is called a magic square.
1 | <a href="https://www.c4learn.com/2012/02/magic-square-program.jpg"><img class="aligncenter size-full wp-image-5652" src="https://www.c4learn.com/2012/02/magic-square-program.jpg" alt="Magic Square C Program" width="341" height="333" /></a> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | #include<stdio.h> #include<conio.h> int main() { int size = 3; int matrix[3][3]; // = {{4,9,2},{3,5,7},{8,1,6}}; int row, column = 0; int sum, sum1, sum2; int flag = 0; printf("\nEnter matrix : "); 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++) { printf("\n"); for (column = 0; column < size; column++) { printf("\t%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("\nMagic square"); else printf("\nNo Magic square"); return 0; } |
Output :
1 2 3 4 5 6 | Enter matrix : 4 9 2 3 5 7 8 1 6 Entered matrix is : 4 9 2 3 5 7 8 1 6 Magic square |
Note :
1 2 3 | Sum of Row1 = Sum of Row2 [Sum of All Rows must be Same] Sum of Col1 = Sum of Col2 [Sum of All Cols must be Same] Sum of Left Diagonal = Sum of Right Diagonal |