Skip to content
StudyFame

Two-Dimensional Arrays in C

A class timetable has days (rows) and periods (columns). A cinema hall has rows and seat numbers. Data like this needs two numbers to find one box.

A two-dimensional (2D) array stores such table-like data. In this lesson you will declare a matrix, fill it, print it, and see how C keeps it in memory.

What You Will Learn

  • What a 2D array is.
  • How to declare and initialize a 2D array.
  • How to read and print a matrix with nested loops.
  • Row-major order: how a 2D array sits in memory.
  • How to find row sums and column sums.

What is a Two-Dimensional Array in C?

Exam definition: A two-dimensional array is an array of arrays. It stores elements in rows and columns (like a matrix) and each element is accessed with two subscripts: a[row][column].

Memory trick: R comes before C, just like in "Roll Call". In a[i][j], the first index is the row, the second is the column.

Syntax of a 2D Array

data_type name[rows][columns];

int m[2][3];                                 /* 2 rows, 3 columns = 6 ints */

int m[2][3] = { {1, 2, 3}, {4, 5, 6} };      /* row by row (clearest) */
int m[2][3] = { 1, 2, 3, 4, 5, 6 };          /* same thing, filled row-wise */
int m[][3]  = { {1, 2, 3}, {4, 5, 6} };      /* rows can be left out */
int m[2][3] = { 0 };                         /* all zero */
  • Total elements = rows × columns.
  • You may leave out the number of rows, but never the columns. C needs the column count to know where each row starts.

Picture of int m[2][3] = {{1, 2, 3}, {4, 5, 6}};

            col 0   col 1   col 2
row 0   :     1       2       3        m[0][0]  m[0][1]  m[0][2]
row 1   :     4       5       6        m[1][0]  m[1][1]  m[1][2]

Example 1: Read and Print a Matrix

#include <stdio.h>

int main(void)
{
    int m[10][10], rows, cols, i, j;

    printf("Enter rows and columns: ");
    scanf("%d %d", &rows, &cols);

    printf("Enter %d elements row by row:\n", rows * cols);
    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < cols; j++)
        {
            scanf("%d", &m[i][j]);
        }
    }

    printf("The matrix is:\n");
    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < cols; j++)
        {
            printf("%4d", m[i][j]);
        }
        printf("\n");                /* new line after each row */
    }

    return 0;
}

Output

Enter rows and columns: 2 3
Enter 6 elements row by row:
1 2 3
4 5 6
The matrix is:
   1   2   3
   4   5   6

Code Explanation

  1. int m[10][10] reserves a 10 × 10 grid. We use only rows × cols of it.
  2. The outer loop (i) picks a row. The inner loop (j) walks across the columns of that row.
  3. scanf("%d", &m[i][j]) reads one element into row i, column j.
  4. %4d prints each number in a 4-character space, so the columns line up.
  5. printf("\n") after the inner loop moves to the next line when a row is finished.

How a 2D Array is Stored in Memory (Row-Major Order)

Memory is one long line, not a grid. C stores a 2D array row after row. This is called row-major order.

m[2][3] = { {1, 2, 3}, {4, 5, 6} }, int = 4 bytes, base address 1000

Element :  m[0][0] m[0][1] m[0][2] m[1][0] m[1][1] m[1][2]
Value   :     1       2       3       4       5       6
Address :   1000    1004    1008    1012    1016    1020
            |-------- row 0 ------| |-------- row 1 ------|

Exam formula: Address of a[i][j] = base + (i × columns + j) × element size. Example: m[1][2] = 1000 + (1 × 3 + 2) × 4 = 1020.

Example 2: Marks Table with Row Totals and Column Totals

3 students, 4 subjects. Row total = a student's total. Column total = a subject's total.

#include <stdio.h>

int main(void)
{
    int marks[3][4] = {
        {78, 85, 90, 66},
        {55, 70, 64, 80},
        {92, 88, 76, 95}
    };
    int i, j, rowSum, colSum;

    for (i = 0; i < 3; i++)
    {
        rowSum = 0;
        for (j = 0; j < 4; j++)
            rowSum += marks[i][j];
        printf("Student %d total: %d\n", i + 1, rowSum);
    }

    for (j = 0; j < 4; j++)
    {
        colSum = 0;
        for (i = 0; i < 3; i++)
            colSum += marks[i][j];
        printf("Subject %d total: %d\n", j + 1, colSum);
    }

    return 0;
}

Output

Student 1 total: 319
Student 2 total: 269
Student 3 total: 351
Subject 1 total: 225
Subject 2 total: 243
Subject 3 total: 230
Subject 4 total: 241
  • For row sums, the outer loop is the row (i). For column sums, swap the loops: the outer loop is the column (j).
  • Reset the sum to 0 inside the outer loop, so each row (or column) starts fresh.

Important Points to Remember

  • A 2D array uses two indexes: a[row][column].
  • Total elements = rows × columns; size in bytes = rows × columns × element size.
  • Row count can be left out in initialization, the column count cannot.
  • C stores 2D arrays in row-major order.
  • Use nested loops: outer for rows, inner for columns.

Common Mistakes Beginners Make

MistakeWhat happensFix
int m[2][] = {...};Compile errorAlways give the column count
Writing m[i, j]Comma operator: means m[j], wrongUse m[i][j]
Forgetting printf("\n") after each rowWhole matrix prints on one linePrint a newline after the inner loop
Not resetting the row sumTotals keep adding upSet sum = 0 inside the outer loop
Swapping rows and columns in loopsOut-of-bounds when rows ≠ columnsi < rows, j < cols

2D Array Practice Questions

  1. How many elements does int a[4][5] have, and how many bytes (int = 4 bytes)?
  2. Which dimension can be left out when initializing a 2D array?
  3. What is row-major order?
  4. For int a[3][4] at base address 2000, find the address of a[2][1].
  5. What is m[1][0] after int m[2][2] = {5, 6, 7, 8};?
Show answers
  1. 20 elements, 80 bytes.
  2. The number of rows (first dimension).
  3. Storing a 2D array row by row in memory: all of row 0, then all of row 1, and so on.
  4. 2000 + (2 × 4 + 1) × 4 = 2036.
  5. 7.

Coding Exercise

For the matrix {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, print the sum of the main diagonal (top-left to bottom-right) and the largest element.

Show solution
#include <stdio.h>

int main(void)
{
    int m[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
    int i, j, diag = 0, max = m[0][0];

    for (i = 0; i < 3; i++)
    {
        diag += m[i][i];                 /* row == column on the diagonal */
        for (j = 0; j < 3; j++)
        {
            if (m[i][j] > max)
                max = m[i][j];
        }
    }

    printf("Diagonal sum = %d\n", diag);
    printf("Largest = %d\n", max);
    return 0;
}
Diagonal sum = 15
Largest = 9

Quick Quiz: Two-Dimensional Arrays (MCQ)

  1. In a[i][j], i stands for:

    A) Column   B) Row   C) Size   D) Address

  2. Which is valid?

    A) int a[][] = {1, 2};   B) int a[2][] = {1, 2};   C) int a[][2] = {1, 2};   D) None

  3. C stores 2D arrays in:

    A) Column-major order   B) Row-major order   C) Random order   D) Reverse order

  4. Number of elements in char s[3][10]:

    A) 13   B) 30   C) 10   D) 3

  5. Value of m[0][2] for int m[2][3] = {1, 2, 3, 4, 5, 6};

    A) 2   B) 3   C) 4   D) 6

Show answers
  1. B: row.
  2. C: only the row count may be left out.
  3. B: row-major order.
  4. B: 30.
  5. B: 3.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

2D arrayArray of arrays: rows × columns
Accessa[row][column]
Can omitRows only, never columns
Memory order in CRow-major
Address of a[i][j]base + (i × cols + j) × size
Main diagonalElements where i == j

Frequently asked questions

What is a two-dimensional array?
An array of arrays that stores data in rows and columns, accessed with two subscripts.
Why must the column size be given?
C needs it to calculate where each row starts in memory.
What is the difference between row-major and column-major order?
Row-major stores row by row (C, C++); column-major stores column by column (Fortran, MATLAB).

Remember

  • Row before Column: a[r][c].
  • Outer loop = rows, inner loop = columns.

Next Topic

Next lesson: Passing Arrays to Functions in C. You will pass 1D and 2D arrays to functions and see why the function can change them.