easy
1 views

Find the Sum of All Elements in a Matrix

Calculate the sum of all integer elements in a given R×C matrix.

Understand the Problem

Problem Statement

You are given a matrix of size R×C containing integers. Write a program to find the sum of all elements present in the matrix.

Note: Make sure to read the input matrix correctly and find the sum of all elements in the matrix as specified in the question.

Constraints

  • 2 ≤ R, C ≤ 50
  • -1000 ≤ Each integer value in the matrix ≤ 1000
  • All input values are integers
  • Matrix dimensions R and C are provided on the first line
  • Matrix elements are provided row by row

Examples

Example 1
Input
3 4
5 10 25 8
12 9 7 6
11 14 18 22
Output
170
Explanation

The sum of all elements is: 5+10+25+8+12+9+7+6+11+14+18+22 = 170.

Example 2
Input
4 3
30 40 5
16 28 35
55 90 15
10 25 60
Output
384
Explanation

The sum of all elements is: 30+40+5+16+28+35+55+90+15+10+25+60 = 384.

Solution

#include <stdio.h>

int main() {
    int R, C;
    scanf("%d %d", &R, &C);
    
    int matrix[50][50];
    
    // Read matrix elements
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }
    
    // Calculate sum of all elements
    int sum = 0;
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++) {
            sum += matrix[i][j];
        }
    }
    
    // Output result
    printf("%d\n", sum);
    
    return 0;
}
Time:O(R×C) - We visit each element exactly once
Space:O(R×C) for the matrix storage + O(1) for the sum variable
Approach:

1. Read R and C from standard input using scanf
2. Declare a 50×50 matrix to store input (sufficient for given constraints)
3. Use nested for loops to read R×C integers into the matrix
4. Initialize sum = 0 to accumulate the total
5. Use another nested loop to iterate through all matrix elements and add each to sum
6. Print the final sum using printf
7. Return 0 to indicate successful execution

Visual Explanation

Loading diagram...