C++ Multidimensional Arrays

A multidimensional array in C++ is an array containing more than one dimension. The most common type is the two-dimensional array, which can be visualized as a table or matrix with rows and columns. Multidimensional arrays are used to store data in a structured format.

Syntax

data_type array_name[size1][size2];

Where:

  • data_type – Type of elements (e.g., int, float, char).
  • array_name – Name of the array.
  • size1 – Number of rows.
  • size2 – Number of columns.

Example: Declaring and Initializing a 2D Array

#include <iostream>
using namespace std;

int main() {

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

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

    return 0;
}

Output

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

Example: Printing as a Table

#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

Important Notes

  • Multidimensional arrays can have two or more dimensions, e.g., 3D arrays.
  • Array indices start from 0 for each dimension.
  • Access elements using array_name[row][column] syntax.

Next Topic

Next, learn about C++ Strings.