Wonder Square or Magic Square:
import java.util.Scanner;
class Magic_Square
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
{
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();
}
}
}

0 Comments
Please don't enter any spam link in comment box.
Emoji