Compute sum of all elements in 2 D array in C

In C programming, computing the sum of all elements in a 2D array involves traversing through each element using nested loops and accumulating the values. This is a fundamental operation when working with matrices and tabular data.

Syntax

datatype array_name[rows][columns];

For example: int arr[3][4]; creates a 2D array with 3 rows and 4 columns, containing 12 elements total.

Example 1: Sum of All Elements

Following is the C program to calculate the sum of all elements in a 2D array −

#include <stdio.h>

int main() {
    int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int sum = 0;
    int i, j;
    
    printf("2D Array elements:<br>");
    for(i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            printf("%d ", arr[i][j]);
            sum += arr[i][j];
        }
        printf("<br>");
    }
    
    printf("Sum of all elements: %d<br>", sum);
    return 0;
}
2D Array elements:
1 2 3 
4 5 6 
7 8 9 
Sum of all elements: 45

Example 2: Sum of Even and Odd Elements

This example demonstrates how to calculate separate sums for even and odd elements in a 2D array −

#include <stdio.h>

int main() {
    int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int evenSum = 0, oddSum = 0;
    int i, j;
    
    printf("Array elements:<br>");
    for(i = 0; i < 2; i++) {
        for(j = 0; j < 3; j++) {
            printf("%d ", arr[i][j]);
            
            if(arr[i][j] % 2 == 0) {
                evenSum += arr[i][j];
            } else {
                oddSum += arr[i][j];
            }
        }
        printf("<br>");
    }
    
    printf("Sum of even elements: %d<br>", evenSum);
    printf("Sum of odd elements: %d<br>", oddSum);
    printf("Total sum: %d<br>", evenSum + oddSum);
    return 0;
}
Array elements:
1 2 3 
4 5 6 
Sum of even elements: 12
Sum of odd elements: 9
Total sum: 21

Key Points

  • Use nested loops to traverse all elements: outer loop for rows, inner loop for columns
  • Initialize sum variable to 0 before starting the calculation
  • Array indexing starts from 0: arr[0][0] to arr[rows-1][columns-1]
  • Time complexity: O(rows × columns), Space complexity: O(1)

Conclusion

Computing the sum of 2D array elements is straightforward using nested loops. This technique forms the foundation for more complex matrix operations and statistical calculations on tabular data.

Updated on: 2026-03-15T13:15:36+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements