Multidimensional Arrays

Lesson 5.3: Multidimensional Arrays


In the previous lesson, you learned about one-dimensional arrays, which store elements in a single row. Now, we'll explore multidimensional arrays, which can store elements in multiple dimensions – like a table (2D), a cube (3D), or even higher dimensions.


Two-Dimensional Arrays (2D Arrays)


The Concept:


A 2D array is essentially an array of arrays. You can visualize it as a table with rows and columns.

Each element in a 2D array is accessed by two indices: one for the row and one for the column.

Declaration:


C

data_type arrayName[numRows][numCols];

Example:

C

int matrix[3][4];   // Declares a 2D array with 3 rows and 4 columns


Initialization:

C

int matrix[2][3] = {

    {1, 2, 3},  // Row 0

    {4, 5, 6}   // Row 1

};

Accessing Elements:

C

int element = matrix[1][2];  // Accesses the element in the second row (index 1) and third column (index 2)


Three-Dimensional Arrays (3D Arrays)


The Concept:


A 3D array is an array of 2D arrays. You can visualize it as a stack of tables.

Each element is accessed by three indices: one for the depth, one for the row, and one for the column.

Declaration:


C

data_type arrayName[numDepths][numRows][numCols];


Example:

C

int cube[2][3][4];   // A 3D array with 2 depths, 3 rows, and 4 columns per depth/row.


Multidimensional Array Manipulation


You can perform various operations on multidimensional arrays similar to how you work with 1D arrays:


Iteration: Use nested loops to access and process each element.

C

for (int i = 0; i < 3; i++) {  // Iterate through rows

    for (int j = 0; j < 4; j++) { // Iterate through columns

        printf("%d ", matrix[i][j]);

    }

    printf("\n");  // Newline after each row

}

Functions: Pass multidimensional arrays to functions (remember to pass the number of columns).

C

void printMatrix(int matrix[][4], int rows) { /* ... */ }

Applications


Multidimensional arrays are useful for representing:


Tables: Store tabular data like spreadsheets or game boards.

Matrices: Perform matrix operations in mathematics and scientific computing.

Images: Represent images as 2D arrays of pixels.

3D Models: Store 3D coordinates of objects in graphics and simulations.

Example: A Simple 2D Array


C

#include <stdio.h>


int main() {

    int table[2][3] = {

        {10, 20, 30},

        {40, 50, 60}

    };


    for (int i = 0; i < 2; i++) {

        for (int j = 0; j < 3; j++) {

            printf("%d\t", table[i][j]); // \t for tab separation

        }

        printf("\n");

    }

    return 0;

}


Let me know if you'd like any clarification or want to see more advanced use cases for multidimensional arrays.

Course Syllabus