import java.io.*;
public class spiral
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the value of n:");
int n=Integer.parseInt(br.readLine());
int a[][]=new int[n][n];
int i,j,x=1,p=0,q=n-1;
while(x<=(n*n))
{
for(i=p;i<=q;i++)
{
a[p][i]=x;
x++;
}
for(i=(p+1);i<=q;i++)
{
a[i][q]=x;
x++;
}
for(i=(q-1);i>=p;i--)
{
a[q][i]=x;
x++;
}
for(i=(q-1);i>=(p+1);i--)
{
a[i][p]=x;
x++;
}
p++;
q--;
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
0 comments:
Post a Comment