Stages in Working with a 2D Array
-
Declaration Stage
First, we declare the 2D array along with any other variables, constants, or 1D arrays needed. For example, a 2D array nameddatawith 4 rows and 4 columns can be declared with datatypestring. A separate 1D array can store the headings for the columns, which will be used during input and output. -
Input Stage
We use nested loops: the outer loop for rows and the inner loop for columns. Users enter data for each cell in the grid, except for columns meant for calculations (like the total column). The OUTPUT command can display prompts using placeholders, for example,Enter {heading} data, where the heading is taken from the 1D heading array. -
Calculation Stage
In this stage, a loop iterates through the rows, and calculations are performed using the relevant columns. For example, the value in column 2 (quantity) is converted to an integer, multiplied by the value in column 3 (price, also converted to integer), and the result is stored in column 4 (total). It is recommended to keep the calculation stage separate for better readability and management. -
Heading Stage
Before displaying the data, the headings stored in the heading array are output as labels, such as Product Name, Quantity, Price, and Total. This helps organize the displayed data and makes it easy to understand. -
Output Stage
Finally, two nested loops (row-wise and column-wise) are used to display the data. Spaces are added between column values for readability, and a blank line is output after each row to structure the table properly.
Key Points
-
A 2D array stores data in rows and columns, making it suitable for tabular data.
-
Nested loops are essential for input, processing, and output.
-
Always keep calculations separate from input and output for easier handling.
-
Column headings help in identifying the data clearly when displayed.
By following these stages, you can effectively use 2D arrays to store, process, and display structured data.
