-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMagic_square.java
52 lines (52 loc) · 1.16 KB
/
Magic_square.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;
public class Magic_square
{
int m[][];
int size;
public void Magic_square(int s)
{
m=new int[size=s][s];
}
public void Show()
{
for(int i=0;i<m.length;i++)
{
for(int j=0;j<m[i].length;j++)
{
System.out.printf("%4d",m[i][j]);
}
System.out.println();
}
}
public void fill()
{
int ch=1;
int r=0;
int c=size/2;
while(ch<=(size*size))
{
m[r][c]=ch++;
r--;
c--;
if(r<0&&c>=0)
r=size-1;
else if(r>=0&&c<0)
c=size-1;
else if((r<0&&c<0)||(m[r][c]>0))
{
r+=2;
c+=1;
}
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of rows and columns=");
int a=sc.nextInt();
Magic_square obj=new Magic_square();
obj.Magic_square(a);
obj.fill();
obj.Show();
}
}