Answer to Question #251750 in Java | JSP | JSF for guru

Question #251750

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


1
Expert's answer
2021-10-16T11:03:51-0400
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


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
APPROVED BY CLIENTS