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.*;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a Number N: ");
int n = scan.nextInt();
for(int i = 0; i<n; i++)
{
int first_row = (n*(i+1));
for(int j = 0; j< n; j++)
{
int value = first_row;
if(value>9)
{
System.out.print(value+" ");
}
else{
System.out.print(value+" ");
}
first_row = first_row -(i+1);
}
System.out.println();
}
}
}
Comments
Leave a comment