Let us learn how to print or generate magic square matrix in C programming language. A magic square is actually a multi – dimensional matrix.

#### What is a Magic Square Matrix?

A magic square is a matrix, which consists of an arrangement of distinct non – repeating integers in a Matrix form, where the sum of the every row, column, major and minor diagonals is same.

This sum is, therefore, called as a **Magic Constant**. A magic square has the same number of rows and columns.

Normally, magic squares work only for **odd integers**. However, you can modify the c program to print the magic square of even numbers too.

#### Example of Magic Square

4 9 2

3 5 7

8 1 6

Sum of Rows = 15

Sum of Columns = 15

Sum of Major Diagonal = 15

Sum of Minor Diagonal = 15

#### C Program To Generate Magic Square Matrix using Functions

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 | #include<stdio.h> #include<string.h> void check_magic_square(int limit); int main() { int num; printf("\nEnter an Odd Number:\t"); scanf("%d", &num); check_magic_square(num); return 0; } void check_magic_square(int limit) { int num, sum, i, j; int matrix[limit][limit]; memset(matrix, 0, sizeof(matrix)); j = limit - 1; i = limit / 2; for(num = 1; num <= limit * limit;) { if((i == -1) && (j == limit)) { j = limit - 2; i = 0; } else { if(j == limit) { j = 0; } if(i < 0) { i = limit - 1; } } if(matrix[i][j]) { j = j - 2; i++; continue; } else { matrix[i][j] = num++; } j++; i--; } sum = (limit * (limit * limit + 1)) / 2; printf("\nSum of Each Row:\t%d\n", sum); printf("\nSum of Each Column:\t%d\n", sum); printf("\nSquare Matrix\n"); for(i = 0; i < limit; i++) { for(j = 0; j < limit; j++) { printf("%d\t", matrix[i][j]); } printf("\n"); } } |

#### Output

If you have any doubts or compilation errors in this C program to display magic square, let us know about it in the comment section below.

Is there any kind of similarity between Magic Number and Magic Square Matrix?

please tell me its logic