Given a number N, create a 2D arrays with n rows and n columns. Now inspect the matrix pattern below and come up with a formula to populate the array for any give NXN matrix.
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
int a = 0;
Scanner scan=new Scanner(System.in);
int size=0;
System.out.println("Please provide size of matrix and press Enter: ");
size=scan.nextInt();
int[][]arr = new int [size][size];
scan.close();
for(int i = 0; i<arr.length; i++){
for(int j = 0; j<arr[i].length; j++){
arr[0][j] = a++;
arr[i][arr[i].length-1] = a++;
arr[arr.length-1][j] = a++;
arr[i][0] = a++;
arr[1][j] = a++;
a++;
}
}
for(int i = 0; i<arr.length; i++){
for(int j = 0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Comments
Leave a comment