Tutorial Study Image

Multi-dimensional arrays in C++


August 27, 2022, Learn eTutorial
1235

This tutorial will teach you how to use multi-dimensional arrays in C++. Specifically, how to declare, access, and utilize them effectively within our program.

What do you mean by multi-dimensional arrays in C++?

When an array has more than one dimension, it is said to be a multi-dimensional array. It is a multi-level array made up of other arrays. The 2D array, also known as a two-dimensional array, is the most basic multi-dimensional array.  A matrix or a table with rows and columns are other names for a two-dimensional array.

In C++, multidimensional arrays are also known as rectangular arrays. It can be either two or three-dimensional. The data is stored in a tabular format (row* column), also known as a matrix.

We can create a multidimensional array in C++ by creating an array of an array. 

An N-dimensional array declaration

An N-dimensional array declaration in its most general form is :


data_type array_ name[size1][size2]...[sizeN];
 
  • data_type : The type of data that will be stored in the array.
  • array_name: The array's name
  • size1, size2,…size N : it mainly determines the dimension’s sizes

Two-dimensional array: int two_d[30][40];

Three-dimensional array: int three_d[50][60][70];

For  an example: int x[2][5];
x is a two-dimensional array in this case. It has a maximum capacity of 10 elements.

Size of Multidimensional Arrays:

By simply multiplying the dimensions of the array, we can determine how many elements are present in total. In the above example, there are 10 elements in total which are obtained simply by multiplying their dimensions.

Multi-dimensional arrays in C++

Two-Dimensional Arrays

The multidimensional array can be expressed most simply as a two-dimensional array.Two-dimensional arrays comprise rows and columns, just like a matrix. Essentially, a list of one-dimensional arrays makes up a two-dimensional array. In order to declare a two-dimensional integer array of size x,y, the syntax is given below:


type arrayName [ x ][ y ];
 

Where the type can be any valid C++ data type as well as the  arrayName would be a valid C++ identifier

A table with x number of rows and y number of columns can be thought of as a two-dimensional array. A two-dimensional array with 3 rows and 4 columns is illustrated below.

Multi-dimensional arrays in C++

Here, the table is a 2-dimensional array that holds 12 integer values in 3 rows and 4 columns. While declaring two-dimensional arrays both row size and column size must be enclosed in square brackets. 

Since a is the name of the array and i and j are the subscripts that individually identify each element in each element in the array a is therefore identified by an element name in the form of a[i][j].

How to initialize two-dimensional arrays in C++?

There are two types of the process by which a 2D array can be initialized.

  1. Compile-time initialization of 2D Array
  2. Runtime initialization of 2D Array

1. Compile-time initialization of 2D Array

As previously discussed initialization can be done during declaration and it takes the form

data_type array_name [row] [column]= {value_1st_element,value_2nd_element,3rd.....};

for instance,


int table [2] [3]={

    {10,20,30};

    {40,50,60};      

}

The same can be defined as follows in a single line which is more convenient and easy.


int table[2][3]={10,20,30,40,50,60};

C++ provides a means to declare an array by leaving the first index blank(row) to be blank whereas it is mandatory to specify the second index (column). The following example shows that in the 2-dimensional array, table, row size is left blank while providing the column size.


int table[][3]={10,20,30,40,50,60};

The compiler does not raise any error as this statement is a valid one and means that any number of rows can be initialized in C++. But in case if column size is not mentioned the compiler will raise an error.

int table[][3]  // Valid

int table[3][]   // Not Valid

Two Dimensional Array after initialization can be best visualized as follows.

Array

2. Runtime initialization of 2D Array

We can accomplish runtime initialization of a 2 Dimensional array with the help of cin function. This can be viewed by examining the following program. 

#include <iostream>
using namespace std;

int main()
{
    int i, j, r, c;
    int M[5][5];

    cout <<"Enter number of rows : ";
    cin >>r;
    cout <<"Enter number of columns :";
    cin >>c;
    cout <<"\n";
    /* Input data to matrix */
    for (i = 0; i < r; i++)
    {
        for (j = 0; j < c; j++)
        {
            cout <<"Data in M[" << i <<"]" <<"[" << j <<"] = ";
            cin >>M[i][j];
        }
 cout <<"\n";

    }

    /* Display the matrix */
    for (i = 0; i < r; i++)
    {
        for (j = 0; j < c; j++)
        {
            cout <<M[i][j];
            cout << "  " ;
        }
        cout <<"\n";
    }

    return 0;
}

Output:

Enter number of rows : 2
Enter number of columns :2
Data in M[0][0] = 4
Data in M[0][1] = 5
Data in M[1][0] = 2
Data in M[1][1] = 6
4  5  
2  6 

This program gives you a clear picture of the 2D array. The array, M[2][2], holds 4 elements with 2 rows and 2 columns. Since the program is to display a 2 x2 matrix, the number of rows and columns is mentioned as 2. Next elements to each position are allocated and finally, the matrix is displayed with the use of cout function and nested for loop.

Accessing Elements of a Two-Dimensional Array

The subscripts, that is a row index and column index of the array, are used to access an element in a two-dimensional array.

For example,

int val = a[2][3];

The fourth element will be taken from the array's third row by the statement above. 

Accessing Elements of a Two-Dimensional Array


#include <iostream>
using namespace std;
 
int main () {
   // this ia an array with 5 rows and 2 columns.
   int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
 
   // output each array element's value                      
   for ( int i = 0; i < 5; i++ )
      for ( int j = 0; j < 2; j++ ) {
      
         cout << "a[" << i << "][" << j << "]: ";
         cout << a[i][j]<< endl;
      }
 
   return 0;
}

Output:

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

As previously stated, arrays can have any number of dimensions, though it is likely that the majority of the arrays you create will be of one or two dimensions

Three-dimensional arrays in C++

In C++ programming we can work with arrays having more than two dimensions. a 3-dimensional array takes the syntax

data_type array_name [row][column][pages]= {value_1st_element,value_2nd_element,3rd.....};

For instance,

int arr[10][10][10];

This array will allocate 10X10X10=1000 elements in the memory of the compiler.

The 3D array can be viewed as given below.

Array

How to initialize of 3 Dimensional Array

The initialization of a 3D array is more similar to a 2D array. Observe the below example:


int test[3][3][3] = {
    {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}},
    {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}},
    {{19, 20, 21}, {22, 23, 24}, {25, 26, 27}}
};

This can be visualized as below in the expanded form.

Array

Example of a 3-dimensional array

Let's take an example of a 3D array


int test[2][3][4] = { 0, -3, 9, 11,3, 4, 2, 3, 13, 4, 56, 3,23, 12, 23, 2,  5, 9, 3, 5, 5, 1, 4, 9};

The following is a better way to initialize a three-dimensional array:


int test[2][3][4] = { 
  { {0, -3, 9, 11}, {3, 4, 2, 3}, {13, 4, 56, 3} },
  {{23, 12, 23, 2}, {5, 9, 3, 5}, {5, 1, 4, 9} }
};

Take note of the three-dimensional array's dimensions.

Multi-dimensional arrays in C++
  1. The value for the first dimension is 2. As a result, the two elements that comprise the first dimension seem to be:
    Multi-dimensional arrays in C++
  2. The value for the second dimension is 3. It is important to note that the first dimension's elements each have three components or elements.
    Multi-dimensional arrays in C++
  3. Finally, each of the second dimension's elements contains four int numbers:
    Multi-dimensional arrays in C++

C++ program that stores and displays the value entered by the user in a three-dimensional array.


#include <iostream>
using namespace std;

int main() {
    // This array have the capacity to store upto 12 elements (2x3x2)
    int test[2][3][2] = {
                            {
                                {11, 12},
                                {13, 14},
                                {15, 16}
                            }, 
                            {
                                {17, 18}, 
                                {19, 20}, 
                                {21, 22}
                            }
                        };

    // Displaying the values with proper index.
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 2; ++k) {
                cout << "test[" << i << "][" << j << "][" << k << "] = " << test[i][j][k] << endl;
            }
        }
    }

    return 0;
}

Output:

test[0][0][0] = 11
test[0][0][1] = 12
test[0][1][0] = 13
test[0][1][1] = 14
test[0][2][0] = 15
test[0][2][1] = 16
test[1][0][0] = 17
test[1][0][1] = 18
test[1][1][0] = 19
test[1][1][1] = 20
test[1][2][0] = 21
test[1][2][1] = 22

However, because we are manipulating three dimensions, we use a nested for loop with three total loops rather than just two:

  • The first dimension of the array is accessed by the outer loop, which runs from I == 0 to I == 1.
  • The second dimension of the array is accessed by the middle loop, which runs from j == 0 to j == 2.
  • the third dimension of the array is accessed by the innermost loop, which runs from k == 0 to k == 1.

As we can see, the array's complexity grows exponentially with the number of dimensions.

The following are the limitations of a multidimensional array:

  • It is impossible to remove or delete any elements from an array
  • If large array size is specified but we don't know how many elements need to be stored in the memory beforehand, then there will be memory waste.

Advantages of multi-dimensional array

  • Benefits include the ability to represent multiple data items of the same type using a single name.

  • It can be used to create other data structures such as linked lists, stacks, queues, trees, graphs, and so on.

  • Matrixes are represented using multidimensional arrays.

Disadvantages of multi-dimensional array

  • We must know ahead of time how many elements will be stored in the array.
  • A static structure is an array. It denotes that the array has a fixed size. 
  • The memory allocated to the array cannot be increased or decreased.
  • Because an array has a fixed size, if we allocate more memory than is required, the memory space will be wasted. And if we allocate less memory than is required, we will have a problem.
  •  Array elements are stored in sequential memory locations.
  • Insertions and deletions are therefore extremely difficult as well as time-consuming.