🔖 2D Array in C – Matrix Tutorial for Beginners

⬅️ Previous

🧠 What is a 2D Array?

A 2D (two-dimensional) array is like a table or matrix with rows and columns. It’s ideal for storing grid-like data such as marks, matrices, or a chessboard.

📌 Syntax of a 2D Array in C

data_type array_name[rows][columns];

Example:

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

✅ Initializing a 2D Array

1. Inline Initialization


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

2. Input using loops

You can use nested loops to input values into a 2D array.

🧪 Full Example: Input and Output from a 2D Array


#include <stdio.h>

int main() {
    int i, j;
    int matrix[2][3];

    // Input values
    printf("Enter values for 2x3 matrix:\n");
    for(i = 0; i < 2; i++) {
        for(j = 0; j < 3; j++) {
            printf("Element [%d][%d]: ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }

    // Display values
    printf("\nThe matrix is:\n");
    for(i = 0; i < 2; i++) {
        for(j = 0; j < 3; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}

🎯 Sample Output


Enter values for 2x3 matrix:
Element [0][0]: 10
Element [0][1]: 20
Element [0][2]: 30
Element [1][0]: 40
Element [1][1]: 50
Element [1][2]: 60

The matrix is:
10  20  30
40  50  60

🔁 Common Operations on 2D Arrays

1. Sum of All Elements


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

🔚 Summary Table

FeatureDescription
TypeMust be the same for all elements
Accessarray[row][column]
Common UsesMatrices, tables, grid-based logic
Index StartsFrom 0 for both rows and columns
2D array in C, Two dimensional array tutorial, C matrix program, How to use 2D array, C array input output, Nested loop array, Table in C, C language basics, Matrix operations in C

Tags: 2D Array, C Programming, Matrix in C, Array Tutorial, C Language, Prog

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