Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Magic Square (http://www.go4expert.com/articles/magic-square-t8690/)

deniz 2Jan2010 15:30

Re: Magic Square
 
so, where can i get the solution of this tedious magic square program?..

deniz 2Jan2010 16:24

Re: Magic Square
 
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();
        }

    }
}


deniz 2Jan2010 16:26

Re: Magic Square
 
Shabbir, could you check this one? I'm not quite sure if this gonna work out,eh.. Thanks..

shabbir 2Jan2010 18:10

Re: Magic Square
 
Quote:

Originally Posted by deniz (Post 62586)
Shabbir, could you check this one? I'm not quite sure if this gonna work out,eh.. Thanks..

For What?

deniz 13Jan2010 13:41

Re: Magic Square
 
Quote:

Originally Posted by shabbir (Post 62593)
For What?

i dont know how to create a magic square program in java. i need it badly..thanks


All times are GMT +5.5. The time now is 14:09.