multi dimensional arrays in cpp

9/13/2025

multi dimensional arrays in cpp

Go Back

Multi-Dimensional Arrays in C++ Tutorial

multi dimensional arrays in cpp

Introduction

Multi-dimensional arrays in C++ are arrays that contain more than one dimension. They are useful for storing tabular or grid-like data, such as matrices, tables, or game boards.

The most commonly used multi-dimensional array is the two-dimensional array.


What is a Multi-Dimensional Array?

A multi-dimensional array is an array of arrays. Each element is accessed using multiple indices.

General Syntax:

dataType arrayName[size1][size2]...[sizeN];
  • size1 – Number of rows

  • size2 – Number of columns (for 2D)

  • sizeN – Additional dimensions if needed


Example – Two-Dimensional Array

#include <iostream>
using namespace std;

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

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Output:

1 2 3
4 5 6

Example – Three-Dimensional Array

#include <iostream>
using namespace std;

int main() {
    int cube[2][2][2] = {
        {{1, 2}, {3, 4}},
        {{5, 6}, {7, 8}}
    };

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 2; k++) {
                cout << cube[i][j][k] << " ";
            }
            cout << endl;
        }
        cout << "---" << endl;
    }
    return 0;
}

Output:

1 2
3 4
---
5 6
7 8
---

Memory Representation

  • Multi-dimensional arrays are stored in row-major order in memory.

  • The elements are stored contiguously.

  • For example, matrix[2][3] stores elements in the order:
    matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2]


Advantages of Multi-Dimensional Arrays

  • Organize data in tabular or grid form

  • Easy to represent mathematical matrices

  • Useful in game boards, graphs, and scientific computations


Limitations

  • Fixed size at compile time

  • Consumes more memory for large dimensions

  • Complex indexing for higher dimensions


Conclusion

Multi-dimensional arrays in C++ are essential for storing and processing data in table-like structures. Two-dimensional arrays are the most common, but you can extend to three or more dimensions when needed.