0
0
Cprogramming~5 mins

Two-dimensional arrays in C

Choose your learning style9 modes available
Introduction
Two-dimensional arrays help you store data in a table-like form with rows and columns, like a grid or spreadsheet.
When you want to store a matrix of numbers, like in math or graphics.
When you need to keep track of a chessboard or game board state.
When you want to represent a table of data with rows and columns.
When you want to store pixel colors in an image.
When you want to organize data in rows and columns for easy access.
Syntax
C
/* Define a 2D array with 3 rows and 4 columns */
int array_name[3][4];

/* Access element at row 1, column 2 */
int value = array_name[1][2];
The first number is the number of rows, the second is the number of columns.
Indexing starts at 0, so row 1 means the second row.
Examples
A 2x3 matrix initialized with values.
C
int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};
A 3x3 matrix where all elements are set to zero.
C
int empty[3][3] = {0};
A 2D array with only one row and four columns.
C
int single_row[1][4] = { {10, 20, 30, 40} };
A 2D array with four rows and one column.
C
int single_column[4][1] = {
    {1},
    {2},
    {3},
    {4}
};
Sample Program
This program creates a 3x3 grid, prints it, changes the middle element, and prints the grid again.
C
#include <stdio.h>

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

    printf("Grid before change:\n");
    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 3; col++) {
            printf("%d ", grid[row][col]);
        }
        printf("\n");
    }

    // Change the center element
    grid[1][1] = 99;

    printf("\nGrid after change:\n");
    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 3; col++) {
            printf("%d ", grid[row][col]);
        }
        printf("\n");
    }

    return 0;
}
OutputSuccess
Important Notes
Accessing elements is fast because memory is stored in a continuous block.
Time complexity to access any element is O(1).
Be careful with indexes to avoid going outside the array bounds, which causes errors.
Use two nested loops to process all elements in the 2D array.
Use 2D arrays when you need fixed-size tables; for dynamic sizes, consider pointers and dynamic memory.
Summary
Two-dimensional arrays store data in rows and columns like a table.
You access elements using two indexes: row and column.
They are useful for grids, matrices, and tables.