C Two Dimensional Arrays

A two dimensional (2D) array is like a table with rows and columns. It is used for matrices, marks of many students in many subjects and game boards.

Declare and initialize

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

This is 2 rows and 3 columns. The element in row 1 and column 2 is matrix[1][2], and its value is 6. Both indexes start from 0.

Print a 2D array

#include <stdio.h>

int main(void) {
    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};

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

Output:

Output of the above program is

1 2 3
4 5 6

Add two matrices

#include <stdio.h>

int main(void) {
    int a[2][2] = {{1, 2}, {3, 4}};
    int b[2][2] = {{5, 6}, {7, 8}};
    int sum[2][2];

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

Output:

Output of the above program is

6 8
10 12

Transpose of a matrix

In a transpose, rows become columns.

#include <stdio.h>

int main(void) {
    int m[2][3] = {{1, 2, 3}, {4, 5, 6}};

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

Output:

Output of the above program is

1 4
2 5
3 6

Note: In memory a 2D array is stored row by row, as one long block. Only the first size can be skipped when you initialize: int m[][3] is allowed, but int m[2][] is not.

Next: C Passing Arrays to Functions.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.