CategoryC Program

C Program to find the sum of all elements in a matrix

Learn how to calculate the sum of every element in a C matrix using a two-dimensional array, nested loops, and a safe accumulator.

To find the sum of all elements in a matrix, visit every row and column and add each value to a running total.

For example:

Matrix:
 5 -2  7
 0  4 -1

Sum = 5 + (-2) + 7 + 0 + 4 + (-1) = 13

The matrix may be square or rectangular, and its elements may be positive, negative, or zero.

C Program to Find the Sum of Matrix Elements

#include <stdio.h>

#define MAX_ROWS 10
#define MAX_COLUMNS 10

int main(void) {
    int matrix[MAX_ROWS][MAX_COLUMNS];
    int rows;
    int columns;
    long long sum = 0;

    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;
            }

            sum += matrix[row][column];
        }
    }

    printf("Sum of all matrix elements: %lld\n", sum);

    return 0;
}

Sample Output

Enter the number of rows and columns: 2 3
Enter 6 matrix elements row by row:
5 -2 7
0 4 -1
Sum of all matrix elements: 13

How the Program Works

The variable sum begins at zero:

long long sum = 0;

Two nested loops visit every active position in the matrix. Immediately after an element is read, its value is added to the running total:

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

When both loops finish, every element has contributed exactly once, so sum contains the matrix total.

Dry Run

Consider this 2 × 3 matrix:

 5 -2  7
 0  4 -1

The accumulator changes as follows:

PositionValueSum beforeSum after
[0][0]505
[0][1]-253
[0][2]7310
[1][0]01010
[1][1]41014
[1][2]-11413

The final sum is 13.

Why Are Nested Loops Required?

A matrix has two dimensions. The outer loop selects a row, and the inner loop visits each column in that row.

If the matrix has r rows and c columns, the inner statement runs:

r × c times

That is exactly the number of elements in the matrix.

Why Add Each Value While Reading?

The matrix total can be calculated during input because each element is already available at that moment. This avoids a second pair of nested loops devoted only to summation.

The program still stores the values in matrix, making them available for later operations. If the total were the only required result, the array could be omitted and each input value could instead be read into one temporary variable.

Why Initialize the Sum to Zero?

An accumulator must have a known starting value. Zero is the additive identity:

0 + value = value

If sum were left uninitialized, it would contain an indeterminate value, and adding matrix elements to it would produce an invalid result.

Why Use long long for the Sum?

Each matrix element is an int, but the sum of many int values can exceed the int range. A long long accumulator provides a wider range:

long long sum = 0;

During sum += matrix[row][column], the matrix value is converted to long long before it is added to the accumulator. This reduces overflow risk when the matrix contains large values.

The fixed 10 × 10 limit also bounds the number of additions, but using a wider accumulator remains the safer design.

Rectangular and Square Matrices

The algorithm does not require equal dimensions. It works for all of these shapes:

  • 3 × 3 square matrix
  • 2 × 5 rectangular matrix
  • 1 × 6 row matrix
  • 6 × 1 column matrix

The loop bounds come from the separately entered rows and columns values.

What Happens with a 1 × 1 Matrix?

Both loops run once, and the only element is also the sum:

Matrix: 42
Sum:    42

No special case is required.

Negative Numbers and Zero

Negative values reduce the running total, while zero leaves it unchanged:

Matrix:
-3  0
 8 -5

Sum = -3 + 0 + 8 - 5 = 0

Ordinary integer addition handles all three kinds of values.

Can the Final Sum Be Negative?

Yes. If the combined magnitude of the negative elements is greater than the positive elements, the result is negative:

Matrix:
-8  2
-4  1

Sum = -9

A negative result does not indicate an error.

Why Validate the Dimensions?

The matrix is declared with MAX_ROWS rows and MAX_COLUMNS columns. Accepting a larger dimension would make the loops access memory outside the array.

The program rejects dimensions below 1 and above the declared capacity before reading any elements:

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

Why Check Every scanf Call?

The dimension input must convert two integers, while each element input must convert one. Checking the return value prevents the program from using uninitialized data when non-numeric input is supplied.

For example:

if (scanf("%d", &matrix[row][column]) != 1) {
    printf("Invalid matrix element.\n");
    return 1;
}

Sum of All Elements Versus Matrix Addition

These are different operations:

  • Sum of all elements: Produces one scalar value from one matrix.
  • Addition of two matrices: Produces another matrix by adding corresponding elements.

For a matrix containing 1, 2, 3, 4, the element total is 10. Matrix addition would require a second matrix of the same dimensions.

Alternative: Sum After Reading the Matrix

If input and processing must be separate, first read every value and then perform another traversal:

long long sum = 0;

for (int row = 0; row < rows; row++) {
    for (int column = 0; column < columns; column++) {
        sum += matrix[row][column];
    }
}

This version gives the same result. It makes sense when matrix input is handled elsewhere or when several calculations are performed after the complete matrix is available.

Extending the Program to Row and Column Sums

The same traversal can calculate more detailed totals:

  • Reset a rowSum before each inner loop to find the sum of every row.
  • Maintain one accumulator per column to find column sums.
  • Add only positions where row == column to find the main-diagonal sum of a square matrix.

The complete-matrix sum is the simplest form because every visited element is included.

Time and Space Complexity

For a matrix with r rows and c columns:

  • Time complexity: O(r × c) because every element is read and added once.
  • Matrix storage: O(MAX_ROWS × MAX_COLUMNS) for the fixed declaration; the active data occupies O(r × c) positions conceptually.
  • Extra working space: O(1) because the summation uses one accumulator beyond the matrix and loop variables.

Any correct algorithm must inspect every element at least once, so the linear-in-element-count running time is optimal.

Common Mistakes

  • Forgetting to initialize sum to zero.
  • Resetting sum inside either loop and losing earlier values.
  • Adding only one row or one column because one loop is missing.
  • Using int for a total that may exceed its range.
  • Using <= rows or <= columns and accessing outside the matrix.
  • Accepting dimensions larger than the declared capacity.
  • Confusing the sum of all elements with adding two matrices.
  • Making a second traversal even when the total can be calculated during input.

By adding each value as it is read, the program calculates the sum of all matrix elements in one traversal with a constant amount of additional working memory.