0
Light Poster
so, where can i get the solution of this tedious magic square program?..
0
Light Poster
Code:
```public class MagicSquare {

public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (N % 2 == 0) throw new RuntimeException("N must be odd");

int[][] magic = new int[N][N];

int row = N-1;
int col = N/2;
magic[row][col] = 1;

for (int i = 2; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
// don't change col
}
magic[row][col] = i;
}

// print results
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (magic[i][j] < 10)  System.out.print(" ");  // for alignment
if (magic[i][j] < 100) System.out.print(" ");  // for alignment
System.out.print(magic[i][j] + " ");
}
System.out.println();
}

}
}```

Last edited by shabbir; 2Jan2010 at 18:10.. Reason: Code blocks
0
Light Poster
Shabbir, could you check this one? I'm not quite sure if this gonna work out,eh.. Thanks..
0
Go4Expert Founder
Quote:
Originally Posted by deniz
Shabbir, could you check this one? I'm not quite sure if this gonna work out,eh.. Thanks..
For What?
0
Light Poster
Quote:
Originally Posted by shabbir
For What?
i dont know how to create a magic square program in java. i need it badly..thanks