Multi-dimensional arrays
Multi-dimensional arrays
Two-Dimensional Arrays
In the previous chapter, we learned how to work with one-dimensional arrays, which represent a set of elements arranged in a single line. Now let's move on to more complex data structures - two-dimensional arrays.
Definition of Two-Dimensional Arrays
A two-dimensional array represents a table or grid of elements that are organized in rows and columns. Each element of a two-dimensional array has two indices: one for the row and one for the column.
To declare a two-dimensional array, use the following syntax:
Working with Two-Dimensional Arrays
Let's look at an example of a two-dimensional array representing a 3x3 table with integers:
In this example, we declared a two-dimensional array matrix with three rows and three columns. Each element of the array has two indices:
- one for the row
- one for the column
For example, element matrix[0][0] is located in the upper left corner of the table.
Assigning Values to Two-Dimensional Array Elements
We can assign values to elements of a two-dimensional array like this:
Now each element of the matrix array has its own value.
Getting Values of Two-Dimensional Array Elements
We can also get values of two-dimensional array elements using their indices:
The output will be as follows:
Thus, two-dimensional arrays allow us to store data in tabular form and conveniently access elements by their coordinates.
Using Loops with Two-Dimensional Arrays
For working with two-dimensional arrays, it's very convenient to use nested loops:
Two-Dimensional Array Initialization During Declaration
You can also initialize a two-dimensional array immediately upon declaration:
Or in one line:
User Input into Two-Dimensional Array
Practical Applications of Two-Dimensional Arrays
Two-dimensional arrays are often used for:
- Representing matrices in mathematics
- Storing data in tabular form
- Creating game fields (e.g., for tic-tac-toe)
- Working with images (pixels as array elements)
Example: Finding Maximum Element
Conclusion
Two-dimensional arrays are a powerful tool for working with tabular data. They extend the capabilities of one-dimensional arrays, allowing you to organize data in rows and columns, making them ideal for many practical programming tasks.