Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Magic Square
The magic square is a square matrix, whose order is odd and where the sum of the elements for each row or each column or each diagonal is same.

The sum of each row or each column or each diagonal can be found using this formula. n(n2+ 1)/2
Here are the rules to construct a magic square −
- We will start from the middle column of the first row, of the matrix, and always go to the top left corner to place next number
- If the row exceeds, or the row is not in the matrix, then, change the column as left column and place the number at last row of the matrix, and go for top left corner again.
- If the column exceeds, or the column is not in the matrix, then change the row as top row and place the number at last column of that matrix, then go to the top left corner again.
- When the top left corner is not vacant or both row and column exceeds the range, then place the number at the bottom of the last-placed number.
Input and Output
Input: The order of the matrix 5 Output: 15 8 1 24 17 16 14 7 5 23 22 20 13 6 4 3 21 19 12 10 9 2 25 18 11
Algorithm
createSquare(mat, r, c)
Input: The matrix.
Output: Row and Column.
Begin count := 1 fill all elements in mat to 0 range := r * c i := 0 j := c/2 mat[i, j] := count //center of top row while countExample
#include#include using namespace std; void createSquare(int **array, int r, int c) { int i, j, count = 1, range; for(i = 0; i > row; col = row; matrix = new int*[row]; for(int i = 0; i |
Output
Enter the order(odd) of square matrix :5 15 8 1 24 17 16 14 7 5 23 22 20 13 6 4 3 21 19 12 10 9 2 25 18 11
Advertisements
