Multidimensional Array
Multi-dimensional arrays are those which have more than one dimension. A multi-dimensional array is defined in much the same manner as a one-dimensional array, except that a separate pair of square brackets are required for each subscript or dimension or index. Thus, a two-dimensional array will require two pairs of square brackets, and so on. The two-dimensional array is also called a matrix. A multi-dimensional array can be defined as follows
storage_class data_type array_name[dim1] [dim2] ... [dimn]
Here, dim1, dim2 …… dimn are positive valued integer expressions that indicate the number of array elements associated with each subscript. An m*n two-dimensional array can be thought of as a table of values having m rows and n rows. For example, int X[3][3] can be shown as follows.
Contents
Declaration of a two-dimensional array
Like a one-dimensional array, a two-dimensional array must also be declared before using it. The syntax for declaration is
[storage class] data_type arary_name[row_size][col_size]
Example:
int matrix[2][3]; // matrix is 2-D array which has 2 rows and 3 columns and it contains 6 elements
Initialization of 2-D array
Like one dimensional array, multi-dimensional arrays can be initialized at the time of array definition or declaration. A few examples of 2-D array initialization are:
- int marks[2][3] = { 2, 4, 6, 8, 10, 12 };
- int marks[2][3] = { { 2, 4, 6 }, {8, 10, 12} };
Accessing 2-D array elements
- arr[0][0] – first element
- arr[0][1] – second element
- arr[0][2] – third element
- arr[1][0] – fourth element
- arr[1][1] – fifth element
- arr[1][2] – sixth element
Example: 2-Dimensional Array
#include <iostream>
using namespace std;
int main(){
int arr[2][3] = {{2, 4, 6}, {8, 10, 12}};
for(int i=0; i<2;i++){
for(int j=0; j<3; j++){
cout<<"arr["<<i<<"]["<<j<<"] = "<<arr[i][j]<<endl;
}
}
return 0;
}
The output of the above program is:
arr[0][0] = 2
arr[0][1] = 4
arr[0][2] = 6
arr[1][0] = 8
arr[1][1] = 10
arr[1][2] = 12
Three Dimensional Array
Now, We learn how to declare and access a three-dimensional array.
Declaring a 3-D Array
int arr[2][3][2];
Initialization
Like two dimensional array, We can initialize a three-dimensional array in the same way. Here we will learn the methods to learn three-dimensional array.
Method 1:
int arr[2][3][2] = {1, -1 ,2 ,-2 , 3 , -3, 4, -4, 5, -5, 6, -6};
Method 2:
int arr[2][3][2] = {
{ {1,-1}, {2, -2}, {3, -3}},
{ {4, -4}, {5, -5}, {6, -6}}
}
Let’s take one example to make clear concepts on a three-dimensional array.
#include <iostream>
using namespace std;
int main(){
// initializing the three dimensional array
int arr[2][3][2] = {
{ {1,-1}, {2,-2}, {3,-3} },
{ {4,-4}, {5,-5}, {6,-6} }
};
// displaying the three dimensional array values
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 3; y++) {
for (int z = 0; z < 2; z++) {
cout<<arr[x][y][z]<<" ";
}
}
}
return 0;
}
The output of the above program is:
1 -1 2 -2 3 -3 4 -4 5 -5 6 -6