Magic Square Matrix Program in Java and Python
Magic square matrix program with algorithm, explanation, Java solution and simple Python solution for ICSE and ISC students.
Question:
A square matrix is said to be a Magic Square if the sum of each row, each column and each diagonal is the same. Write a program to enter an integer number n. Create a magic square of size n × n and print the elements of the matrix.
Note: n <= 5.


Algorithm:
Step 1: Start.
Step 2: Accept the order n of the square matrix.
Step 3: If n is less than 1 or greater than 5, display an error message and stop.
Step 4: Declare a two-dimensional integer array A[n][n] and initialize all positions to 0.
Step 5: If n is odd, place 1 in the first row and middle column.
Step 6: For each next number, try to move one row upward and one column to the right.
Step 7: If the new row goes above the matrix, wrap it to the last row; if the new column crosses the right boundary, wrap it to the first column.
Step 8: If the calculated cell is already occupied, move two rows down and one column left from the previous position, then store the number.
Step 9: If n is even, first fill the matrix row-wise with numbers from 1 to n × n.
Step 10: For the even case, swap the corresponding corner elements on the primary diagonal and secondary diagonal as done in the original program.
Step 11: Display the matrix row by row with proper spacing.
Step 12: Stop.
Explanation:
The program uses two different construction logics because odd-order and even-order magic squares are handled differently. The matrix array stores the final arrangement, while the variables i and j track the current row and column.
For an odd value of n, the method used is the standard upward-right movement. The next number is normally placed one row above and one column to the right. Boundary checks are important because moving above the first row must continue from the last row, and moving beyond the last column must continue from the first column.
When the upward-right cell is already filled, the program does not overwrite it. It moves down from the previous position and continues placing the next number. This occupied-cell check is what prevents duplicate placements and keeps the magic-square pattern intact.
For an even value of n, this older method first fills natural numbers row by row and then swaps diagonal corner values. This matches the original program logic and gives the sample arrangement shown in the post for small even sizes.
A magic square is filled so that rows, columns and diagonals have the same sum. For odd order magic squares, a common method begins from the middle of the first row and moves diagonally upward and right. If the move goes outside the matrix, it wraps around. If the target cell is already filled, the position is adjusted according to the rule, often by moving down. The program’s correctness depends on these movement rules and on ensuring every number is placed exactly once.
Java Program:
/**
* The class Magic_Matrix creates a Square Matrix of size n*n and fills it
* in such a way that sum of every row and every column is the same
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/
import java.util.Scanner;
class Magic_Matrix
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("\n\nEnter the size of the matrix : ");
int n=sc.nextInt();
if(n>5)
System.out.println("Enter a number between 1 to 5 ");
else
{
int A[][]=new int[n][n]; // Creating the Magic Matrix
int i,j,k,t;
/*Initializing every cell of the matrix with 0 */
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
A[i][j] = 0;
}
}
/* When the size of the matrix is Odd */
if(n%2!=0)
{
i=0;
j = n/2;
k = 1;
while(k<=n*n)
{
A[i][j] = k++;
i--; // Making one step upward
j++; // Moving one step to the right
if(i<0 && j>n-1) // Condition for the top-right corner element
{
i = i+2;
j--;
}
if(i<0) // Wrapping around the row if it goes out of boundary
i = n-1;
if(j>n-1) // Wrapping around the column if it goes out of boundary
j = 0;
if(A[i][j]>0) // Condition when the cell is already filled
{
i = i+2;
j--;
}
}
}
/* When the size of the matrix is even */
else
{
k = 1;
/* Filling the matrix with natural numbers from 1 till n*n */
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
A[i][j] = k++;
}
}
j = n-1;
for(i=0; i<n/2; i++)
{
/* swapping corner elements of primary diagonal */
t = A[i][i];
A[i][i] = A[j][j];
A[j][j] = t;
/* swapping corner elements of secondary diagonal */
t = A[i][j];
A[i][j] = A[j][i];
A[j][i] = t;
j--;
}
}
/* Printing the Magic matrix */
System.out.println("The Magic Matrix of size "+n+"x"+n+" is:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
}
}
}Equivalent Python Program:
n = int(input("Enter the size of the matrix: "))
if n < 1 or n > 5:
print("Enter a number between 1 and 5")
else:
# A stores the final magic square matrix.
A = [[0 for j in range(n)] for i in range(n)]
if n % 2 != 0:
# Odd order magic square starts at first row and middle column.
i = 0
j = n // 2
k = 1
while k <= n * n:
A[i][j] = k
k = k + 1
old_row = i
old_col = j
# Move upward and right for the next number.
i = i - 1
j = j + 1
# Wrap the row and column when they cross the boundary.
if i < 0:
i = n - 1
if j == n:
j = 0
# If the cell is already filled, move down from the old position.
if A[i][j] != 0:
i = old_row + 1
j = old_col
else:
k = 1
# Fill the matrix with natural numbers row by row.
for i in range(n):
for j in range(n):
A[i][j] = k
k = k + 1
j = n - 1
for i in range(n // 2):
# Swap primary diagonal corner values.
t = A[i][i]
A[i][i] = A[j][j]
A[j][j] = t
# Swap secondary diagonal corner values.
t = A[i][j]
A[i][j] = A[j][i]
A[j][i] = t
j = j - 1
print("The Magic Matrix of size", n, "x", n, "is:")
for i in range(n):
for j in range(n):
print(A[i][j], end="\t")
print()Output:
Leave a Reply
Your email address will not be published. Comments are reviewed before appearing publicly.