Explanation
This Java program demonstrates how to create, populate, and display a two-dimensional (2D) array where the size and the elements are provided by the user at runtime.
The logic follows these steps:
- Initialization: The program uses the
Scannerclass to capture input from the keyboard. - Dimension Input: It prompts the user to enter the number of rows and columns. These values determine the size of the "matrix."
- Array Declaration: A 2D integer array named
numis declared and instantiated using the user-provided dimensions (new int[rows][cols]). - Data Entry (Input Phase): The program uses "nested loops." The outer
forloop iterates through each row, while the innerforloop iterates through each column within that row. At every intersection (positioni, j), the program asks the user for an integer and stores it in the array. - Data Display (Output Phase): Another set of nested loops is used to traverse the array. The inner loop prints elements of a single row separated by spaces. After the inner loop finishes a row,
System.out.println()is called to move to the next line, ensuring the output looks like a mathematical matrix. - Cleanup: Finally, it closes the
Scannerobject to free up system resources.