Chapter 18 of 37

Multidimensional Arrays

In the previous topic, we learned about one-dimensional arrays, where data is stored in a single sequence.

But what if we want to store data in the form of rows and columns, like a table or matrix?

That's where multidimensional arrays are useful.

What is a Multidimensional Array?

A multidimensional array is an array that has more than one dimension.

The most commonly used type is a two-dimensional array (2D array).

For example:

int matrix[2][3];

This creates an array with:

  • 2 rows

  • 3 columns

It can be visualized as:

        Column
        0   1   2
      ┌───┬───┬───┐
Row 0│10 │20 │30 │
      ├───┼───┼───┤
Row 1│40 │50 │60 │
      └───┴───┴───┘

Declaring a 2D Array

The syntax is:

data_type array_name[rows][columns];

For example:

int matrix[2][3];

This can store 6 integers in total.

We can also initialize it while declaring:

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

Accessing Elements

To access an element, we specify its row and column index.

Remember that indexing starts from 0.

printf("%d", matrix[0][1]);

Output:

20

Here:

  • 0 → first row

  • 1 → second column

So matrix[0][1] refers to 20.


Using Loops with 2D Arrays

Nested loops are commonly used to work with multidimensional arrays.

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

for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 3; j++)
    {
        printf("%d ", matrix[i][j]);
    }

    printf("\n");
}

Output:

10 20 30
40 50 60

Here, the outer loop handles the rows, while the inner loop handles the columns.

Outer loop → Rows
Inner loop → Columns

More Than Two Dimensions

C also supports arrays with three or more dimensions.

For example:

int data[2][3][4];

This creates a three-dimensional array.

However, beginners will mostly work with 1D and 2D arrays, especially when learning basic C.

Common Uses

Multidimensional arrays are useful for representing:

  • Matrices

  • Tables

  • Student marks

  • Game boards

  • Grids

  • Images and other structured data

For example, a student's marks in different subjects can be represented as:

          Math  C  Java
John       80   75   90
Jason      85   88   92

In Simple Words

A multidimensional array is an array with multiple dimensions, commonly used to store data in rows and columns.

The most important form is the 2D array:

int matrix[2][3];

Just remember:

First index → Row

Second index → Column