Wonder Square or Magic Square

Wonder Square or Magic Square:


import java.util.Scanner;
class Magic_Square
{
       public static void main(String args[])
       {
              Scanner sc=new Scanner(System.in);
              System.out.println("Enter odd size of Matrix");
              int n=sc.nextInt();
              int ar[][]=new int[n][n];
              int row=0,col=n/2,num=1;
              while(num<=n*n)
              {
                     ar[row][col]=num;
                     num++;
                     int tempCol=(col+1)%n;
                     int tempRow=(row-1)>=0?row-1:n-1;
                     if(ar[tempRow][tempCol]!=0)
                     {
                            row=(row+1)%n;
                     }
                     else
                     {
                            row=tempRow;
                            col=tempCol;
                     }
              }
              for(int x=0;x<=ar.length-1;x++)
              {
                     for(int y=0;y<=ar[0].length-1;y++)
                     {
                            System.out.print(ar[x][y] + "\t");
                     }
                     System.out.println();
              }
       }
}

Input:
Enter odd size of Matrix
3


Output:
8 1 6

3 5 7

4 9 2


Input:
Enter odd size of Matrix
5


Output:
17 24 1 15

23 5 7 14 16

4 6    13 20 22

10 12 19 21 3

11 18 25 2 9

Post a Comment

0 Comments