- The user is prompted to enter the size of the magic square. If the size is even, the program terminates because magic squares can only be generated for odd sizes.
- An empty 2D array of the given size is created to hold the magic square.
- The starting position for the first number is set to the last row and middle column of the square.
- A loop runs from 1 to n^2, with each iteration placing the current number in the current row and column, and then moving the position diagonally down and right by one cell.
- If the position goes beyond the edges of the square, it wraps around to the opposite edge.
- If the position is already occupied, it moves up two rows and left one column instead.
 
  
  import java.util.Scanner;
public class MagicSquare {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the size of the magic square: ");
        int n = sc.nextInt();
        if (n % 2 == 0) {
            System.out.println("The size must be odd.");
            return;
        }
        int[][] magicSquare = new int[n][n];
        int row = n-1;
        int col = n/2;
        for (int i = 1; i <= n*n; i++) {
            magicSquare[row][col] = i;
            row++;
            col++;
            if (row == n && col == n) {
                row = 0;
                col = n-2;
            }
            else if (row == n) {
                row = 0;
            }
            else if (col == n) {
                col = 0;
            }
            else if (magicSquare[row][col] != 0) {
                row -= 2;
                col--;
            }
        }
        // Print the magic square
        System.out.println("The magic square is:");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(magicSquare[i][j] + " ");
            }
            System.out.println();
        }
    }
}
 
No comments:
Post a Comment