Generating a Magic Square Matrix in Java



Program to print pattern that fetches starting position and then prints diagonally

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Magic {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Please Enter Size of Matrix:");
        int n = Integer.parseInt(br.readLine());
        int i, j, x = 1;
        int a[][] = new int[n][n];
        // default value
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                a[i][j] = 0;
            }
        }
        display(a, n);
        System.out.println("Please enter position:");
        System.out.println("Please enter row position:");
        int r = Integer.parseInt(br.readLine());
        System.out.println("Please enter column position:");
        int c = Integer.parseInt(br.readLine());
        a[r][c] = x++;
        display(a, n);
        r--;
        c++;
        if (r < 0) 
          r = n - 1;
        if (c == n) 
          c = 0;
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                if (a[r][c] == 0) {
                    a[r][c] = x++;
                    int z = r;
                    r--;
                    int y = c;
                    c++;
                    if (r < 0) 
                      r = n - 1;
                    if (c == n) 
                      c = 0;
                    if (a[r][c] != 0) {
                        c = y;
                        z++;
                        r = z;
                        if (r == n) 
                          r = 0;
                    }
                }
            }
        }
        display(a, n);
    }
    static void display(int a[][], int n) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(a[i][j] + " ");
            }
            System.out.print("\n");
        }
    }
}



OUTPUT:


Please Enter Size of Matrix:
3
0 0 0
0 0 0
0 0 0

Please enter position: 
Please enter row position: 0
Please enter column position: 0
1 0 0
0 0 0
0 0 0

1 6 8
5 7 3
9 2 4
Previous Post Next Post