C PROGRAMMING PROGRAM • MATRICES
Calculate Every Matrix Row and Column Sum
Learn how to calculate every matrix row and column sum using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
2 3 1 2 3 4 5 6
Sample output
Row 1 sum = 6 Row 2 sum = 15 Column 1 sum = 5 Column 2 sum = 7 Column 3 sum = 9
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int rows, columns, matrix[10][10];
scanf("%d %d", &rows, &columns);
if (rows < 1 || rows > 10 || columns < 1 || columns > 10) return 1;
for (int row = 0; row < rows; row++)
for (int column = 0; column < columns; column++) scanf("%d", &matrix[row][column]);
for (int row = 0; row < rows; row++) {
int sum = 0;
for (int column = 0; column < columns; column++) sum += matrix[row][column];
printf("Row %d sum = %d\n", row + 1, sum);
}
for (int column = 0; column < columns; column++) {
int sum = 0;
for (int row = 0; row < rows; row++) sum += matrix[row][column];
printf("Column %d sum = %d\n", column + 1, sum);
}
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Row 1 sum = 6 Row 2 sum = 15 Column 1 sum = 5 Column 2 sum = 7 Column 3 sum = 9
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Traverse by rows for row sums and by columns for column sums.
- Display the computed result.
Traverse by rows for row sums and by columns for column sums.
EFFICIENCY
Time and space complexity
Time complexity
O(rows × columns)
Auxiliary space
O(rows × columns)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
