java code for magic square

/
0 Comments

 

  1. 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.
  2. An empty 2D array of the given size is created to hold the magic square.
  3. The starting position for the first number is set to the last row and middle column of the square.
  4. 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.
  5. If the position goes beyond the edges of the square, it wraps around to the opposite edge.
  6. 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();
        }
    }
}

 



You may also like

No comments: