Function matrixSum – CTS PATTERN
Fix syntax errors in the matrixSum function to correctly calculate the sum of all elements in a 2D matrix stored as a 1D array
Understand the Problem
Problem Statement
You are required to correct the syntax of the given code without changing its logic. You can click on Run anytime to check the compilation/execution status of the program. You can use printf to debug your code. The submitted code should be logically/syntactically correct and pass all test cases. Do not write the main() function as it is not required.
Code Approach: For this question, you will need to correct the given implementation. We do not expect you to modify the approach or incorporate any additional library methods.
The function matrixSum(int *matrix, int m, int n) is supposed to return the sum of elements of the input array matrix having m rows and n columns.
The function looks fine but fails to return the desired result due to compilation and logical errors.
Your task is to fix the program so that it passes all test cases.
Constraints
- 1 ≤ m ≤ 1000 (number of rows)
- 1 ≤ n ≤ 1000 (number of columns)
- Matrix elements are stored in row-major order as a 1D array
- Matrix pointer is not null
- Each matrix element can be any integer value
- Function should handle edge cases where m or n is 1
Examples
matrix = [1, 2, 3, 4, 5, 6], m = 2, n = 321The matrix is [[1, 2, 3], [4, 5, 6]]. Sum = 1 + 2 + 3 + 4 + 5 + 6 = 21
matrix = [10, 20, 30], m = 1, n = 360The matrix is [[10, 20, 30]]. Sum = 10 + 20 + 30 = 60
matrix = [5, 15], m = 2, n = 120The matrix is [[5], [15]]. Sum = 5 + 15 = 20
Solution
int matrixSum(int *matrix, int m, int n)
{
int i, j, sum = 0;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
sum += matrix[i * n + j];
}
}
return sum;
}Step-by-step explanation:
- Function signature: Uses
int *matrixto accept a pointer to the first element of the matrix array - Initialize sum:
sum = 0to accumulate the total - Outer loop: Iterates through each row (i from 0 to m-1)
- Inner loop: For each row, iterates through each column (j from 0 to n-1)
- Array indexing:
matrix[i * n + j]correctly calculates the position of element at row i, column j in the 1D array - Accumulate sum: Adds each element to the running total
- Return result: Returns the final sum after processing all elements