public class MagicSquare3 { public static void main (String[] argv) { // Create space for the array, but not assign individual values: int[][] square = new int [3][3]; assignValues (square); print (square); } // Current row/column and next row/column. static int row, col; static int nextRow, nextCol; static void assignValues (int[][] A) { int size = A.length; if (size % 2 != 1) { System.out.println ("size must be odd"); System.exit (0); } // Start with middle in top row. row = 0; col = size/2; A[row][col] = 1; for (int n=2; n<=size*size; n++) { // Go up diagonally to the right. computeNext (size); if (A[nextRow][nextCol] == 0) { // Place next number here if unoccupied. A[nextRow][nextCol] = n; } else { // Else, place directly below current number. nextRow = row + 1; nextCol = col; A[nextRow][nextCol] = n; } // Update. row = nextRow; col = nextCol; } //end-for } static void computeNext (int size) { if (row == 0) { // If we're at the top, next row wraps around. nextRow = size - 1; } else { // Otherwise, go to previous row. nextRow = row - 1; } if (col == size-1) { // If we're at the rightmost col, wrap around to leftmost. nextCol = 0; } else { // Otherwise, next column is the one to the right. nextCol = col + 1; } } static void print (int[][] A) { System.out.println ("Square of size " + A.length + ":"); for (int i=0; i