Skip to study material
← Question index

QUESTION 32 · Matrices and Dimensions

Explain the declaration, initialisation and access of two-dimensional arrays.

5 marks

Answer in brief

A two-dimensional array is an array whose elements are themselves arrays. It naturally represents a table of rows and columns.

Declaration and initialisation

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

Access

a[0][0] is 1, a[0][2] is 3 and a[1][1] is 5. The first index selects a row array; the second selects an element within that row. Neither index may leave its own array bounds. a[0][3] is invalid even though another row follows in storage.

Row-major storage

C stores each row contiguously, followed by the next row. The example’s element order is 1, 2, 3, 4, 5, 6. This is called row-major order. A two-dimensional array is not the same type as a pointer to pointer.

Traversal

Use an outer loop for rows and an inner loop for columns. Print a newline after the inner loop to end each row. The program displays the two rows exactly as a table.

Complexity and memory

For r rows and c columns, there are r × c elements. Visiting every element once takes O(rc) time. The array occupies r × c × sizeof(element) C bytes; only loop counters add O(1) auxiliary space. A direct valid access uses O(1) time in the usual model.

Function connection

When passing such an array to a function, the row width must be described correctly so that indexing advances by a complete row. The final topic of this unit explains the fixed-width function form.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>

int main(void)
{
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
    for (int row = 0; row < 2; ++row) {
        for (int col = 0; col < 3; ++col) {
            if (col > 0) { putchar(' '); }
            printf("%d", a[row][col]);
        }
        putchar('\n');
    }
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

1 2 3
4 5 6

Related exam questions

Related questions in the multidimensional arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • July 2021 · Q3(a) · 7 marks

    Using a two-dimensional array, write a C program to transpose a 2 × 2 matrix.

    Paper P04 · page 1
  • September 2023 · Q1(d) · 1 marks

    What is a two-dimensional array?

    Paper P06 · page 1

View this category in the exam question bank →