C Program To Find The Sum Of Each Row Each Column Of A Mxn Matrix
Matrices are fundamental data structures in programming, often used to represent grids, tables, or transformations. A common operation involves calculating sums across their rows and columns, which can provide valuable insights into the data. In this article, you will learn how to write a C program to efficiently find the sum of each row and each column of an MxN matrix.
Problem Statement
The challenge is to take a given two-dimensional array (matrix) of size M rows by N columns and compute two distinct sets of sums:
- The sum of all elements within each individual row.
- The sum of all elements within each individual column.
Example
Consider the following 3x3 matrix:
1 2 3
4 5 6
7 8 9
Expected Output:
- Row 1 Sum: 1 + 2 + 3 = 6
- Row 2 Sum: 4 + 5 + 6 = 15
- Row 3 Sum: 7 + 8 + 9 = 24
- Column 1 Sum: 1 + 4 + 7 = 12
- Column 2 Sum: 2 + 5 + 8 = 15
- Column 3 Sum: 3 + 6 + 9 = 18
Background & Knowledge Prerequisites
To understand and implement this solution, you should be familiar with:
- C Programming Basics: Variables, data types, input/output operations (
printf,scanf). - Arrays: Declaration, initialization, and accessing elements in one-dimensional and two-dimensional arrays.
- Loops:
forloops for iterating through sequences and arrays. - Basic Arithmetic Operations: Addition.
Use Cases or Case Studies
Calculating row and column sums has several practical applications:
- Data Analysis: In a spreadsheet-like dataset, row sums might represent total sales for a product, while column sums represent total sales for a given month.
- Image Processing: In a grayscale image represented as a matrix, row and column sums could indicate average brightness or highlight patterns in specific regions.
- Game Development: In grid-based games, calculating sums can help determine scores in rows/columns, or check for specific patterns (e.g., in Tic-Tac-Toe or Bejeweled).
- Statistical Analysis: Finding marginal totals in contingency tables.
- Matrix Operations: This is a basic building block for more complex matrix operations like finding averages or checking properties.
Solution Approaches
The most straightforward and efficient approach involves using nested loops to iterate through the matrix elements.
Approach 1: Direct Iteration with Nested Loops
This approach uses two sets of nested loops: one to calculate row sums and another to calculate column sums.
One-line summary
Iterate through the matrix using nestedfor loops, accumulating sums for each row and then for each column separately.
Code example
// Matrix Row and Column Sum
#include <stdio.h>
#define ROWS 3
#define COLS 3
int main() {
int matrix[ROWS][COLS] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int i, j;
int row_sum, col_sum;
printf("Original Matrix:\\n");
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%d\\t", matrix[i][j]);
}
printf("\\n");
}
printf("\\n");
// Step 1: Calculate sum of each row
printf("Row Sums:\\n");
for (i = 0; i < ROWS; i++) {
row_sum = 0; // Reset sum for each new row
for (j = 0; j < COLS; j++) {
row_sum += matrix[i][j];
}
printf("Sum of Row %d = %d\\n", i + 1, row_sum);
}
printf("\\n");
// Step 2: Calculate sum of each column
printf("Column Sums:\\n");
for (j = 0; j < COLS; j++) { // Outer loop iterates through columns
col_sum = 0; // Reset sum for each new column
for (i = 0; i < ROWS; i++) { // Inner loop iterates through rows
col_sum += matrix[i][j];
}
printf("Sum of Column %d = %d\\n", j + 1, col_sum);
}
return 0;
}
Sample output
Original Matrix:
1 2 3
4 5 6
7 8 9
Row Sums:
Sum of Row 1 = 6
Sum of Row 2 = 15
Sum of Row 3 = 24
Column Sums:
Sum of Column 1 = 12
Sum of Column 2 = 15
Sum of Column 3 = 18
Stepwise explanation
- Include Header: The
stdio.hheader is included for standard input/output functions likeprintf. - Define Dimensions:
ROWSandCOLSare defined using preprocessor directives to easily change the matrix dimensions. This makes the code more adaptable. - Matrix Initialization: A 2D integer array
matrixis declared and initialized with sample values. You could also take user input for the matrix elements. - Display Matrix: The program first prints the original matrix to the console for clarity, using nested loops.
- Calculate Row Sums:
- An outer
forloop iterates fromi = 0toROWS - 1(for each row).
- An outer
row_sum is initialized to 0 for *each new row* to ensure sums are independent.for loop iterates from j = 0 to COLS - 1 (for each element in the current row).matrix[i][j] (the element at the current row i and column j) is added to row_sum.row_sum holds the total for the current row, which is then printed.- Calculate Column Sums:
- An outer
forloop iterates fromj = 0toCOLS - 1(for each column). Note thatjis now the outer loop counter.
- An outer
col_sum is initialized to 0 for *each new column*.for loop iterates from i = 0 to ROWS - 1 (for each element in the current column).matrix[i][j] (the element at the current row i and column j) is added to col_sum.col_sum holds the total for the current column, which is then printed.- Return 0: Indicates successful program execution.
Conclusion
Calculating the sum of each row and column of a matrix is a fundamental operation in many computing applications. By employing simple nested for loops, we can efficiently traverse a 2D array and accumulate the necessary sums. This method is clear, concise, and applicable to matrices of any dimension.
Summary
- Matrix row and column sums are calculated by iterating through elements.
- Row sums are found by fixing the row index and varying the column index.
- Column sums are found by fixing the column index and varying the row index.
- Nested
forloops provide an effective way to implement this traversal. - Resetting the sum variable for each new row or column is crucial for correctness.