Write a Java program to print this matrix.
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Java Program
import java.util.Scanner;
public class Arrays {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter N");
int n=s.nextInt();
int[][] a=new int[n][n];
int left=0,right=n-1,top=0,bottom=n-1;
int count=0;
while(count<n*n)
{
for(int i=left;i<=right;i++)
{
count++;
a[top][i]=count;
}
top++;
for(int i=top;i<=bottom;i++)
{
count++;
a[i][right]=count;
}
right--;
for(int i=right;i>=left;i--)
{
count++;
a[bottom][i]=count;
}
bottom--;
for(int i=bottom;i>=top;i--)
{
count++;
a[i][left]=count;
}
left++;
}
for(int i=0;i<=n-1;i++)
{
for(int j=0;j<=n-1;j++)
{
System.out.printf("%4d",a[i][j]);
}
System.out.println();
}
}
}
0 Comments