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.
5 4 3 2 1
10 8 6 4 2
15 12 9 6 3
20 16 12 8 4
25 20 15 10 5
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the a Number N: ");
int N = sc.nextInt();
for(int i = 0; i<N; i++)
{
int my_first_row_matrix_value = (N*(i+1));
for(int j = 0; j< N; j++)
{
int value_to_insert_to_matrix = my_first_row_matrix_value;
//Print the matrix value
if(value_to_insert_to_matrix>9)
{
//Use less spacing if a number has two digits for good formatting
System.out.print(value_to_insert_to_matrix+" ");
}
else{
System.out.print(value_to_insert_to_matrix+" ");
}
//update my_first_row_matrix_value
my_first_row_matrix_value = my_first_row_matrix_value -(i+1);
}
System.out.println();
}
}
}
SAMPLE PROGRAM OUTPUTS
Comments
Leave a comment