C++ Arrays: Multidimensional Arrays
Syntax
A multidimensional array in C++ is defined as:
data_type array_name[size1][size2]...[sizeN];
where data_type
specifies the data type of the elements in the array, array_name
is the name given to the array, and size1
, size2
, ..., sizeN
specify the size of each dimension of the array.
Example
Here's an example of a 2D array of integers with 3 rows and 4 columns:
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Output
The output of the above example array would be:
1 2 3 4
5 6 7 8
9 10 11 12
Explanation
A multidimensional array is essentially an array of arrays. In our example, arr
is a 2D array with 3 rows and 4 columns. We used initializer lists to fill the elements of the array with values.
Use
Multidimensional arrays are useful for representing data in higher dimensions, such as matrices and grids. They are also used in many scientific and mathematical computations.
Important Points
- The size of a multidimensional array must be specified for each dimension.
- Arrays in C++ are zero-indexed, meaning the index of the first element is 0, not 1.
- Accessing elements in a multidimensional array requires specifying the index for each dimension, separated by commas.
Summary
In this page, we learned how to define and use multidimensional arrays in C++. We also saw how they can be useful for representing higher-dimensional data and performing computations. Remember that multidimensional arrays are essentially arrays of arrays, so each element in a multidimensional array can be thought of as an array itself.