# C++ Multidimensional Arrays

### Multidimensional Arrays in C++

An array is defined as a collection of items stored at contiguous memory locations under the same name.In multidimensional arrays,the elements are located using two indexes – row and column.In this section, we will learn about the declaration and initialization of multi-dimensional arrays in C++ and along with it some example codes to learn to implement C++ multidimensional arrays. ## Multidimensional Arrays in C++

In C++ programming language, the multi-dimensional arrays are represented using two indexes i.e. row number and column number respectively.Total number of elements that can be stored in a multidimensional array can be calculated by multiplying the number of rows and columns.

Elements in two-dimensional arrays are commonly referred by a[ i ][ j ] where i is the row number and ‘j’ is the column number.

### Declaration of multi-dimension array

``int p;``

In the above given declaration of the multi dimensional array, p is a 2D array which can hold 12 elements.

### Initialization of multi-dimension array

#### First way:

`int a = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 };`

The elements will be filled in the array in the order, first 3 elements from the left in the first row, next 3 elements in the second row and so on.

#### Second way:

`int a = {{0,1,2}, {3,4,5,}, {6,7,8}};`
• This type of initialization makes use of nested braces. Each set of inner braces represents one row.
• In the above example, there are total of three rows so there are three sets of inner braces.

### Implementation of Multi-dimension Array in C++

#### Example 1:

The following code shows the implementation of multi-dimension array.

Run
```#include<bits/stdc++.h>
using namespace std;
int main()
{
int p = {{2, -5},{4, 0},{9, 1}};
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 2; ++j)
{
cout << "p[" << i << "][" << j << "] = " << p[i][j] << endl;
}
}
return 0;
}

```

#### Output:

```p = 2
p = -5
p = 4
p = 0
p = 9
p = 1
```

#### Example 2:

Run
```#include<bits/stdc++.h>
using namespace std;
int main()
{
int p = {{ {1, 2},{3, 4},{5, 6} }, { {7, 8},{9, 10},{11, 12} }};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {
cout << "p[" << i << "][" << j << "][" << k << "] = " << p[i][j][k] << endl;
}
}
}
return 0;
}

```

#### Output:

```p = 1
p = 2
p = 3
p = 4
p = 5
p = 6
p = 7
p = 8
p = 9
p = 10
p = 11
p = 12
```

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others