CategoryC Program

C Program to read and print elements of a matrix

Learn how to read and print a rectangular matrix in C using a two-dimensional array, validated dimensions, and nested loops.

A matrix is a rectangular arrangement of values organized into rows and columns. In C, a matrix can be stored in a two-dimensional array and processed with nested loops.

For example, a matrix with 2 rows and 3 columns contains six elements:

1 2 3
4 5 6

The program below reads the dimensions, accepts every element row by row, and prints the matrix in the same rectangular layout.

C Program to Read and Print a Matrix

#include <stdio.h>

#define MAX_ROWS 10
#define MAX_COLUMNS 10

int main(void) {
    int matrix[MAX_ROWS][MAX_COLUMNS];
    int rows;
    int columns;

    printf("Enter the number of rows and columns: ");
    if (scanf("%d %d", &rows, &columns) != 2 ||
        rows < 1 || rows > MAX_ROWS ||
        columns < 1 || columns > MAX_COLUMNS) {
        printf("Rows and columns must each be between 1 and 10.\n");
        return 1;
    }

    printf("Enter %d matrix elements row by row:\n", rows * columns);
    for (int row = 0; row < rows; row++) {
        for (int column = 0; column < columns; column++) {
            if (scanf("%d", &matrix[row][column]) != 1) {
                printf("Invalid matrix element.\n");
                return 1;
            }
        }
    }

    printf("The matrix is:\n");
    for (int row = 0; row < rows; row++) {
        for (int column = 0; column < columns; column++) {
            printf("%6d", matrix[row][column]);
        }
        printf("\n");
    }

    return 0;
}

Sample Output

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

How the Program Works

The matrix is declared with enough room for at most 10 rows and 10 columns:

int matrix[MAX_ROWS][MAX_COLUMNS];

The variables rows and columns specify how much of that capacity is used for the current input. If the user enters 2 3, only positions in the first two rows and first three columns are accessed.

Two nested loops visit every active position. The outer loop chooses a row, and the inner loop visits each column in that row.

Reading Matrix Elements

The input loops are:

for (int row = 0; row < rows; row++) {
    for (int column = 0; column < columns; column++) {
        scanf("%d", &matrix[row][column]);
    }
}

For a 2 × 3 matrix, the elements are stored in this order:

Input orderArray position
1stmatrix[0][0]
2ndmatrix[0][1]
3rdmatrix[0][2]
4thmatrix[1][0]
5thmatrix[1][1]
6thmatrix[1][2]

This is called row-by-row or row-major traversal.

Printing the Matrix

Printing uses the same traversal order. Each element is displayed with a field width of six characters:

printf("%6d", matrix[row][column]);

The width helps columns line up when values contain different numbers of digits. After the inner loop finishes one row, the newline is printed:

printf("\n");

Placing this newline outside the inner loop is what makes all elements of a row appear on the same output line.

Understanding Matrix Indices

C array indices begin at zero. In a matrix with rows rows and columns columns:

  • Valid row indices range from 0 to rows - 1.
  • Valid column indices range from 0 to columns - 1.
  • matrix[row][column] selects one element.

For this matrix:

10 20 30
40 50 60

the value 50 is stored at matrix[1][1], which means the second row and second column.

Why Are Nested Loops Needed?

A one-dimensional array needs one index, but a matrix has two dimensions. One loop controls the row, and another controls the column within that row.

For every iteration of the outer loop, the inner loop runs columns times. Therefore, the total number of visited elements is:

rows × columns

Why Validate Both Dimensions?

The declared array has fixed limits. A row count greater than MAX_ROWS or a column count greater than MAX_COLUMNS would cause later loops to access memory outside the matrix.

The program also rejects zero and negative dimensions because a matrix in this example must contain at least one element.

rows < 1 || rows > MAX_ROWS ||
columns < 1 || columns > MAX_COLUMNS

Validation happens before any matrix element is read.

Why Check the Return Value of scanf?

This expression expects two integer conversions:

scanf("%d %d", &rows, &columns) != 2

If the user enters non-numeric data or supplies only one usable integer, the return value is not 2, so the program stops rather than using an uninitialized dimension.

Each element input is checked in the same way and must produce exactly one successful conversion.

Spaces and Line Breaks in Input

For %d, scanf treats spaces, tabs, and newlines as whitespace separators. All of these inputs describe the same 2 × 3 matrix:

1 2 3 4 5 6
1 2 3
4 5 6

Entering one row per line is easier for people to read, but the program does not depend on those line breaks.

Rectangular and Square Matrices

The number of rows does not need to equal the number of columns.

  • A 3 × 3 matrix is square.
  • A 2 × 4 matrix is rectangular.
  • A 1 × 5 matrix is a row matrix.
  • A 5 × 1 matrix is a column matrix.

The same nested loops handle every shape within the configured limits.

Example with Negative Numbers and Zero

Matrix elements are ordinary int values, so negative numbers and zero work without special handling:

Enter the number of rows and columns: 2 2
Enter 4 matrix elements row by row:
-5 0
12 -3
The matrix is:
    -5     0
    12    -3

What Happens with a 1 × 1 Matrix?

Both loops run once:

Enter the number of rows and columns: 1 1
Enter 1 matrix elements row by row:
42
The matrix is:
    42

No special case is necessary.

Fixed-Size Array Versus Variable-Length Array

The program declares a fixed-capacity matrix and validates the active dimensions. This approach is straightforward and supported broadly by C compilers.

C99 also introduced variable-length arrays, allowing a declaration after reading the dimensions:

int matrix[rows][columns];

However, variable-length array support is optional in later C standards, and very large dimensions can exhaust stack space. A fixed maximum makes the storage limit explicit for this beginner example.

How a Matrix Is Stored in Memory

C stores a two-dimensional array row by row. For a 2 × 3 matrix, the logical elements appear contiguously in this order:

matrix[0][0], matrix[0][1], matrix[0][2],
matrix[1][0], matrix[1][1], matrix[1][2]

Traversing columns inside rows follows that layout and generally provides efficient memory access.

Time and Space Complexity

For a matrix with r rows and c columns:

  • Input time complexity: O(r × c) because every element is read once.
  • Output time complexity: O(r × c) because every element is printed once.
  • Total time complexity: O(r × c); two linear passes over the same number of elements remain the same order of growth.
  • Matrix storage: O(MAX_ROWS × MAX_COLUMNS) for the fixed-capacity declaration. Conceptually, the active data occupies O(r × c) positions.
  • Extra working space: O(1) beyond the matrix itself.

Common Mistakes

  • Using one loop and failing to track both rows and columns.
  • Swapping row and column bounds in the nested loops.
  • Allowing dimensions larger than the declared array capacity.
  • Using <= rows or <= columns and accessing one position beyond the matrix.
  • Printing the newline inside the inner loop and placing every element on its own line.
  • Forgetting & before matrix[row][column] in scanf.
  • Assuming that every matrix must be square.
  • Failing to check whether numeric input was read successfully.

By using one loop for rows and another for columns, the program reads and displays every matrix element in its correct position while safely respecting the declared array limits.