Two-Dimensional Arrays in C

A two-dimensional array stores values in rows and columns. For int matrix[3][3], both row and column indexes range from 0 to 2.

Declare and Display a 3×3 Array Top ↑

#include <stdio.h>

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

    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 3; col++) {
            printf("%d ", matrix[row][col]);
        }
        printf("\n");
    }

    return 0;
}

Output

1 2 3
4 5 6
7 8 9

Read Values from the User Top ↑

for (int row = 0; row < 3; row++) {
    for (int col = 0; col < 3; col++) {
        printf("Value [%d][%d]: ", row, col);
        if (scanf("%d", &matrix[row][col]) != 1) {
            printf("Invalid input.\n");
            return 1;
        }
    }
}

Change One Element Top ↑

To double the second row, second column element, use index [1][1] because indexing starts from zero:

matrix[1][1] *= 2;

Add Two Matrices Top ↑

#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 row = 0; row < 2; row++) {
        for (int col = 0; col < 2; col++) {
            sum[row][col] = a[row][col] + b[row][col];
        }
    }

    for (int row = 0; row < 2; row++) {
        for (int col = 0; col < 2; col++) {
            printf("%d ", sum[row][col]);
        }
        printf("\n");
    }

    return 0;
}

Practice Questions Top ↑

  1. Create a 3×3 matrix and read all elements.
  2. Display the matrix with one line per row.
  3. Double the element at row 2, column 2.
  4. Add two 3×3 matrices into a third matrix.
  5. Subtract one matrix from another.
  6. Create a second matrix whose elements are twice the first matrix.

Matrix Sum Matrix Multiplication





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer