Answer to Question #256439 in Java | JSP | JSF for dee

Question #256439

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.


1
Expert's answer
2021-10-27T16:23:47-0400
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();
	            }
	}


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS