Overview of supported operations
Now that we know the logical representation of a multidimensional array, let's look at how to create, update, and traverse one. In most modern programming languages, these operations are very similar and follow the same rules as those of a single-dimensional array.
Construction
Almost all the major programming languages support adding more dimensions to a regular array in one form or another. Since a multidimensional array is just an array, it has a fixed size that cannot be modified after creation. All data items in the array must be of the same data type.
Creating a multidimensional array of fixed size and datatype
Higher-level programming languages like JavaScript and Python inherently only provide a list instead of an array. A list behaves just like an array, but has a dynamic size and can store elements of different data types. Thus, the programmer doesn't need to provide a size when declaring or initializing a multidimensional array.
C++
Java
Typescript
Javascript
Python
Accessing elements
We can access data items in a multidimensional array like a regular array using the subscript operator [] and an index. Since every data item in a multidimensional array is also an array, we chain the subscript operator to access the data item in the internal array. We can continue chaining the subscript operator until we reach a non-array data item.
Multidimensional array elements can be accessed using indices for all dimensions
Different programming languages provide different ways of accessing elements within a multidimensional array. However, the underlying mechanism to access the element is the same.
C++
Java
Typescript
Javascript
Python
Modifying elements
We can modify data items in a multidimensional array in place, just like a regular array. We chain the subscript operator as many times as there are dimensions with the correct indices to access the data item we want to modify and update its value by writing the accessor array[In][In-1]...[I1] on the left-hand side of the assignment operator and the value to be assigned on the right-hand side.
Multidimensional array elements can be modified using indices for all dimensions
Different programming languages implement the underlying operations differently. However, the result is the same.
C++
Java
Typescript
Javascript
Python
Traversal
We need nested loops to iterate over all the indices in every dimension to traverse a multidimensional array. The logic is simple and just an extension of the single-dimensional array traversal.
Traversing a multidimensional array using a nested loop iterative indices for all dimensions
The order of these loops affects the performance of the code depending on the order in which the array items are stored in the memory. We will learn more about this when we learn how a multidimensional array is stored in memory.
C++
Java
Typescript
Javascript
Python