🔢 Multidimensional Arrays

⬅️ Previous

🔢 Multidimensional Arrays in C (2D & More)

📌 What is a Multidimensional Array?

In C, a multidimensional array is an array of arrays. The most common type is the 2D array, which is like a table (rows and columns).

data_type array_name[size1][size2];

Example:

int matrix[3][4]; // 3 rows and 4 columns

🧠 Memory Layout

2D arrays are stored in row-major order in memory:

matrix[0][0], matrix[0][1], ..., matrix[2][3]

🧪 Example: Declaring and Initializing a 2D Array

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

Accessing Elements:

printf("%d", table[1][2]); // Output: 6

🔁 Traversing a 2D Array Using Loops

#include <stdio.h>

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

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

    return 0;
}

✍️ User Input in 2D Array

#include <stdio.h>

int main() {
    int mat[2][2];
    
    printf("Enter 4 numbers:\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            scanf("%d", &mat[i][j]);
        }
    }

    printf("Matrix:\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }

    return 0;
}

📋 More Dimensions

int cube[2][3][4]; // 3D array: 2 layers of 3x4

Access like:

cube[1][2][3] = 99;

📌 Summary Table

Type Syntax Description
1D Array int a[5]; Single row of 5 elements
2D Array int b[3][4]; 3 rows, 4 columns
3D Array int c[2][3][4]; 2 blocks of 3×4 matrices

💡 Tips

  • 2D arrays are commonly used for matrices, tables, or grids.
  • You can initialize partially: int arr[2][3] = {{1}, {4}};
  • Nested loops are essential for input/output.
C multidimensional arrays, 2D array in C, C programming arrays tutorial, array of arrays in C, how to use 3D array in C
Multidimensional Arrays in C with Examples

একটি মন্তব্য পোস্ট করুন