Multidimensional Array

0 orlando52e20512 November 13, 2020

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, dim1dim2 …… 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 can be shown as follows.

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;   // 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, 4, 6, 8, 10, 12 };
• int marks = { { 2, 4, 6 }, {8, 10, 12} };

Accessing 2-D array elements

• arr – first element
• arr – second element
• arr – third element
• arr – fourth element
• arr – fifth element
• arr – sixth element

Example: 2-Dimensional Array

#include <iostream>
using namespace std;

int main(){
int arr = {{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 = 2
arr = 4
arr = 6
arr = 8
arr = 10
arr = 12

Three Dimensional Array

Now, We learn how to declare and access a three-dimensional array.

Declaring a 3-D Array

int arr;

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 = {1, -1 ,2 ,-2 , 3 , -3, 4, -4, 5, -5, 6, -6};

Method 2:

int arr = {

{ {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 = {
{ {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