Explanation
This Java program demonstrates how to create and manipulate a One-Dimensional (1D) Array where the size and the elements are determined by the user at runtime.
The logic follows a linear progression:
- Input Setup: The program uses the
Scannerclass to read input from the keyboard. - Defining Size: It first asks the user how many elements they want to store. This value is used to dynamically allocate memory for the array using the
newkeyword. - Data Collection: A
forloop runs from index0tosize - 1. In each iteration, the program prompts the user for a number and stores it in the corresponding index of the array (num[i]). - Displaying Data: A second
forloop traverses the array from the beginning to the end (usingnum.length) to print each stored value to the console, formatted inside square brackets. - Resource Management: Finally, it closes the
Scannerobject to prevent memory leaks.