Multidimensional Arrays in C++

Multidimensional Arrays

Multidimensional arrays is defined as an array of arrays. Multidimensional arrays contain the data this data are stored in tabular form. Create an array of an array, is known as a multidimensional array.

Syntax of multidimensional array

type arrayName [ x ][ y ];

 

Example of multidimensional array

Two dimensional array:
int two_d[10][20];

Three dimensional array:
int three_d[10][20][30];

 

Two-Dimensional Array

The simplest form of an multidimensional array is two dimensional array. A  2-dimensional array is list of one-dimensional arrays.

 

Syntax of two dimensional array

data_type array_name[x][y];

 

 

Initializing Two-Dimensional Arrays

Method 1:

int arr[2][2] = {1, 2 ,3 ,4 };

 

Method 2:

int arr[2][3] = {{1, 2} , {3,4}};

Accessing Two-Dimensional Array Elements

An element in two dimensional array is accessed by using the subscripts. In 2 dimensional arrays elements are accessed using the row indexes and column indexes.

Example of accessing two dimensional array element

int x[2][1];

Program of accessing two dimensional array element

#include <iostream>
using namespace std;

int main() {
int i,j;
    int test[3][2] = {{1, 2},
                      {3, 4},
                      {5, 6}};

        for (i = 0; i < 3; ++i) {

            for (j = 0; j < 2; ++j) {
            cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;
        }
    }

    return 0;
}

 

Output

test[0][0] = 1
test[0][1] = 2
test[1][0] = 3
test[1][1] = 4
test[2][0] = 5
test[2][1] = 6

Three-Dimensional Array

Program of Three Dimensional array

include<iostream>
using namespace std;
 
int main()
{
    
    int x[2][3][2] =
    {
        { {0,1}, {2,3}, {4,5} },
        { {6,7}, {8,9}, {10,11} }
    };
 
    
    for (int i = 0; i < 2; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            for (int k = 0; k < 2; ++k)
            {
                cout << "Element at x[" << i << "][" << j
                     << "][" << k << "] = " << x[i][j][k]
                     << endl;
            }
        }
    }
    return 0;
}

Output

Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11

Read more, Arrays in C++

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *