# Multi-Dimensional Array in C++ With an Example

## 1. What is Multi-Dimensional array?

We know how often one-dimensional and two-dimensional arrays used in C++. But the dimensions are not limited to only two dimensions. When we access an array with more than two indexes, then we call that array as a multi-dimensional array. When an array is accessed using three indexes, we call that as a ‘3D Array’ and when it is accessed using four indexes; we call it as a ‘4D Array’ and so on.

In this example, we will create a three-dimensional array and then populate values in it. And then we will read it and display the result in the console window.

## 2. Array Declaration

A Three-Dimensional array can be declared as shown below:

In the above example, we declared an array with 3 rows, 3 columns, and 2 slabs. Similarly, you can declare a 4-Dimensional and 5-Dimensional arrays. The first square bracket represents rows, the second square bracket means columns and the third one represents the slabs of rows and columns.

## 3. Writing Multi-Dimensional Arrays

We use three ‘for’ loops to populate the array. First, we populated the first slab with the value of 1. Next, we populated the second slab with the value of 2. To put it differently, we populated two 2-dimensional arrays and stacked it one over the other. Below is the code:

Note, how we formed the loops. The first loop represents iteration over rows and the second one shows iteration over columns and the third one shows iteration over slabs. After we populate the array, it will look like the below:

The array is read the same way it was written. In our example, we read the array slab by slab. In fact, we read our Three-Dimensional array treating it as a two 2-Dimensional arrays. Below is the code that reads the data from the array:

## 5. Completed Code Example

Below is the complete code example:

Output of the above example is below:

Categories: C++

Tags: ,

This site uses Akismet to reduce spam. Learn how your comment data is processed.