Labs ICT
Pro Login

Multi-Dimensional Arrays

A multidimensional array is simply an array of arrays. The most common one is the 2D array — think of it as a table with rows and columns, or a grid on a spreadsheet.

Declaring a 2D Array

You add an extra set of brackets for each dimension. A 2D array needs two sizes — the number of rows and the number of columns:

#include <iostream>

int main() {
  int grid[3][4] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
  };

  std::cout << "Element at row 1, col 2: " << grid[1][2] << "\n";

  grid[0][0] = 99;

  std::cout << "Updated top-left corner: " << grid[0][0] << "\n";
  return 0;
}

The first index is the row, the second is the column. grid[1][2] pulls the value from the second row, third column — which is 7 in this case.

Nested Loops

To walk through every element in a 2D array, you use a nested loop. The outer loop runs through rows, the inner loop runs through columns:

#include <iostream>

int main() {
  int matrix[2][3] = {
    {10, 20, 30},
    {40, 50, 60}
  };

  for (int row = 0; row < 2; row++) {
    for (int col = 0; col < 3; col++) {
      std::cout << matrix[row][col] << " ";
    }
    std::cout << "\n";
  }
  return 0;
}

Each time the outer loop advances one row, the inner loop runs through all the columns in that row. The result is the whole matrix printed row by row.

Higher Dimensions

You can go as deep as you need. A 3D array adds a depth dimension — picture a cube instead of a flat grid. Each extra dimension adds another set of brackets and another level of nesting in your loops.

#include <iostream>

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

  for (int x = 0; x < 2; x++) {
    for (int y = 0; y < 3; y++) {
      for (int z = 0; z < 2; z++) {
        std::cout << cube[x][y][z] << " ";
      }
      std::cout << "\n";
    }
    std::cout << "---\n";
  }
  return 0;
}