Insert Number In Matrix in Spiral form:-
For e.g.:-
Enter the number of elements : 4
The Circular Matrix is:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
For e.g.:-
Enter the number of elements : 4
The Circular Matrix is:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Program:-
import java.io.*;
class InsertNumberInSprial
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number of elements : ");
int n=Integer.parseInt(br.readLine());
int A[][]=new int[n][n];
int entryNum=1, c1=0, c2=n-1, r1=0, r2=n-1;
while(entryNum<=n*n)
{
for(int i=c1;i<=c2;i++)
{
A[r1][i]=entryNum++;
}
for(int j=r1+1;j<=r2;j++)
{
A[j][c2]=entryNum++;
}
for(int i=c2-1;i>=c1;i--)
{
A[r2][i]=entryNum++;
}
for(int j=r2-1;j>=r1+1;j--)
{
A[j][c1]=entryNum++;
}
c1++;
c2--;
r1++;
r2--;
}
/* Printing the Circular matrix */
System.out.println("The Circular Matrix is:");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
}
}
No comments:
Post a Comment