Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Arrays Part 2: Matrices and Grids

Lesson 17 of 53 in the free Foundation of C & C++ notes on Siksha Sarovar, written by Rohit Jangra.

Two-Dimensional Arrays

A 2D array is essentially an "array of arrays." It represents data in rows and columns, like a spreadsheet, a digital image, or a chess board.

Declaration

// data_type name[rows][columns];
int matrix[3][4]; // A grid with 3 rows and 4 columns (12 total items)

Initialization

int grid[2][3] = {
    {1, 2, 3}, // Row 0
    {4, 5, 6}  // Row 1
};

Accessing Elements

You need two indices: one for the row and one for the column.

int val = grid[1][0]; // Accesses the 4 (Row 1, Column 0)

Visual Table Representation

Col 0Col 1Col 2
Row 0[0][0][0][1][0][2]
Row 1[1][0][1][1][1][2]

Processing with Nested Loops

To work with every item in a 2D array, you almost always use two nested for loops.

for (int i = 0; i < rows; i++) {       // Outer loop for rows
    for (int j = 0; j < columns; j++) { // Inner loop for columns
        printf("%d ", matrix[i][j]);
    }
    printf("\n"); // Newline after each row
}

Memory Layout: Row-Major Order

In your computer's RAM, memory is a single long line. Even a 2D array is stored linearly: all of Row 0 first, followed by all of Row 1, and so on.

Multi-Dimensional Arrays

You aren't limited to 2D. You can have 3D (a cube), 4D, or more.

int cube[10][10][10]; // 1000 integers total

While possible, anything above 3D is extremely difficult for humans to visualize and is rarely used in standard business logic.

When passing a 2D array to a function, you must specify the number of columns in the function parameter: void process(int arr[][3]). The compiler needs this to calculate the memory offsets!