- How to calculate the sum of each row in a matrix
- How to calculate the sum of each column in a matrix
- How to use arrays to store row and column sums
- Step-by-step explanation of the program
- Practice exercises to test your understanding
Introduction
In this tutorial, we will learn how to write a C program to find the sum of each row and each column in a matrix.
Finding the sum of rows and columns in a matrix is a fundamental operation in many applications, such as:
- Data Analysis: Summarizing data by rows and columns
- Image Processing: Calculating brightness sums
- Statistics: Finding marginal totals in contingency tables
- Finance: Calculating row and column totals in spreadsheets
š” Key Point: Row sum = sum of all elements in a row. Column sum = sum of all elements in a column. We calculate both by traversing the matrix.
Visual Example
Matrix (3Ć3):
[1 2 3] [4 5 6] [7 8 9]
Row Sums:
Row 0: 1 + 2 + 3 = 6 Row 1: 4 + 5 + 6 = 15 Row 2: 7 + 8 + 9 = 24
Column Sums:
Column 0: 1 + 4 + 7 = 12 Column 1: 2 + 5 + 8 = 15 Column 2: 3 + 6 + 9 = 18
C Program to Find Sum of Each Row and Each Column
#include <stdio.h>
int main() {
int rows, cols, i, j;
// Ask user for matrix dimensions
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Declare matrix and sum arrays
int matrix[rows][cols];
int row_sum[rows];
int col_sum[cols];
// Initialize sum arrays to 0
for(i = 0; i < rows; i++) {
row_sum[i] = 0;
}
for(j = 0; j < cols; j++) {
col_sum[j] = 0;
}
// Read elements into the matrix
printf("\nEnter %d elements:\n", rows * cols);
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("matrix[%d][%d] = ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// Calculate row and column sums
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
row_sum[i] += matrix[i][j]; // Add to row sum
col_sum[j] += matrix[i][j]; // Add to column sum
}
}
// ====== DISPLAY MATRIX ======
printf("\n=== The Matrix (%dĆ%d) ===\n", rows, cols);
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
// ====== DISPLAY ROW SUMS ======
printf("\n=== Row Sums ===\n");
for(i = 0; i < rows; i++) {
printf("Row %d sum: %d\n", i + 1, row_sum[i]);
}
// ====== DISPLAY COLUMN SUMS ======
printf("\n=== Column Sums ===\n");
for(j = 0; j < cols; j++) {
printf("Column %d sum: %d\n", j + 1, col_sum[j]);
}
// ====== DISPLAY MATRIX WITH ROW AND COLUMN SUMS ======
printf("\n=== Matrix with Row and Column Sums ===\n");
// Print column headers
printf("\t");
for(j = 0; j < cols; j++) {
printf("C%d\t", j + 1);
}
printf("Row Sum\n");
// Print matrix with row sums
for(i = 0; i < rows; i++) {
printf("R%d\t", i + 1);
for(j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("%d\n", row_sum[i]);
}
// Print column sums at the bottom
printf("\t");
for(j = 0; j < cols; j++) {
printf("%d\t", col_sum[j]);
}
printf("Total\n");
// Print grand total
int grand_total = 0;
for(i = 0; i < rows; i++) {
grand_total += row_sum[i];
}
printf("\nGrand Total: %d\n", grand_total);
return 0;
}
Sample Output
Enter the number of rows: 3 Enter the number of columns: 3 Enter 9 elements: matrix[0][0] = 1 matrix[0][1] = 2 matrix[0][2] = 3 matrix[1][0] = 4 matrix[1][1] = 5 matrix[1][2] = 6 matrix[2][0] = 7 matrix[2][1] = 8 matrix[2][2] = 9 === The Matrix (3Ć3) === 1 2 3 4 5 6 7 8 9 === Row Sums === Row 1 sum: 6 Row 2 sum: 15 Row 3 sum: 24 === Column Sums === Column 1 sum: 12 Column 2 sum: 15 Column 3 sum: 18 === Matrix with Row and Column Sums === C1 C2 C3 Row Sum R1 1 2 3 6 R2 4 5 6 15 R3 7 8 9 24 12 15 18 Total Grand Total: 45
Example with a 2Ć4 Matrix:
Enter the number of rows: 2 Enter the number of columns: 4 Enter 8 elements: matrix[0][0] = 1 matrix[0][1] = 2 matrix[0][2] = 3 matrix[0][3] = 4 matrix[1][0] = 5 matrix[1][1] = 6 matrix[1][2] = 7 matrix[1][3] = 8 === The Matrix (2Ć4) === 1 2 3 4 5 6 7 8 === Row Sums === Row 1 sum: 10 Row 2 sum: 26 === Column Sums === Column 1 sum: 6 Column 2 sum: 8 Column 3 sum: 10 Column 4 sum: 12 === Matrix with Row and Column Sums === C1 C2 C3 C4 Row Sum R1 1 2 3 4 10 R2 5 6 7 8 26 6 8 10 12 Total Grand Total: 36
Program Explanation
Let's break down the code step by step:
- Include Header File:
#include <stdio.h>includes the standard input/output library. - Declare Variables:
int rows, cols;ā dimensions of the matrixint i, j;ā loop counters
- Declare Arrays:
int matrix[rows][cols];ā the main matrixint row_sum[rows];ā stores sum of each rowint col_sum[cols];ā stores sum of each column
- Initialize Sum Arrays: Sets all elements of
row_sumandcol_sumto 0. - Read Matrix: Uses nested loops to read elements into the matrix.
- Calculate Row and Column Sums:
row_sum[i] += matrix[i][j]ā adds the element to the row sumcol_sum[j] += matrix[i][j]ā adds the element to the column sum
- Display Results: Prints the matrix, row sums, column sums, and a combined table with row/column totals.
- Calculate Grand Total: Sum of all row sums (or all column sums).
- Return:
return 0;indicates successful program execution.
š Note: The grand total is the sum of all elements in the matrix. It can be calculated by summing all row sums or all column sums.
Algorithm to Find Row and Column Sums
Step-by-step algorithm:
- Start
- Read the number of rows (r) and columns (c)
- Create row_sum array of size r, initialized to 0
- Create col_sum array of size c, initialized to 0
- Read r Ć c elements into the matrix
- For
i = 0tor-1:- For
j = 0toc-1:row_sum[i] += matrix[i][j]col_sum[j] += matrix[i][j]
- For
- Print the matrix
- Print all row sums
- Print all column sums
- Print the combined table with row and column totals
- End
Function-Based Approach
Here's a version using separate functions for better code organization:
#include <stdio.h>
void calculateRowSums(int matrix[][10], int rows, int cols, int row_sum[]) {
int i, j;
for(i = 0; i < rows; i++) {
row_sum[i] = 0;
for(j = 0; j < cols; j++) {
row_sum[i] += matrix[i][j];
}
}
}
void calculateColSums(int matrix[][10], int rows, int cols, int col_sum[]) {
int i, j;
for(j = 0; j < cols; j++) {
col_sum[j] = 0;
for(i = 0; i < rows; i++) {
col_sum[j] += matrix[i][j];
}
}
}
void displayMatrix(int matrix[][10], int rows, int cols) {
int i, j;
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int rows, cols, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &rows, &cols);
int matrix[10][10];
int row_sum[10], col_sum[10];
printf("\nEnter %d elements:\n", rows * cols);
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
calculateRowSums(matrix, rows, cols, row_sum);
calculateColSums(matrix, rows, cols, col_sum);
printf("\n=== Matrix ===\n");
displayMatrix(matrix, rows, cols);
printf("\n=== Row Sums ===\n");
for(i = 0; i < rows; i++) {
printf("Row %d: %d\n", i + 1, row_sum[i]);
}
printf("\n=== Column Sums ===\n");
for(j = 0; j < cols; j++) {
printf("Column %d: %d\n", j + 1, col_sum[j]);
}
return 0;
}
Time and Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Reading Matrix | O(r Ć c) | O(1) |
| Calculating Sums | O(r Ć c) | O(1) |
| Overall | O(r Ć c) | O(r + c) |
š» Practice Exercise
Challenge 1: Find the row with the maximum sum and the column with the maximum sum.
Challenge 2: Calculate the sum of the main diagonal and the sum of the secondary diagonal in addition to row and column sums.
š Click to Show Solution for Challenge 1
#include <stdio.h>
int main() {
int rows, cols, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &rows, &cols);
int matrix[rows][cols];
int row_sum[rows], col_sum[cols];
for(i = 0; i < rows; i++) {
row_sum[i] = 0;
}
for(j = 0; j < cols; j++) {
col_sum[j] = 0;
}
printf("\nEnter %d elements:\n", rows * cols);
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
row_sum[i] += matrix[i][j];
col_sum[j] += matrix[i][j];
}
}
// Find row with maximum sum
int max_row_sum = row_sum[0];
int max_row_index = 0;
for(i = 1; i < rows; i++) {
if(row_sum[i] > max_row_sum) {
max_row_sum = row_sum[i];
max_row_index = i;
}
}
// Find column with maximum sum
int max_col_sum = col_sum[0];
int max_col_index = 0;
for(j = 1; j < cols; j++) {
if(col_sum[j] > max_col_sum) {
max_col_sum = col_sum[j];
max_col_index = j;
}
}
printf("\n=== Row Sums ===\n");
for(i = 0; i < rows; i++) {
printf("Row %d: %d\n", i + 1, row_sum[i]);
}
printf("\n=== Column Sums ===\n");
for(j = 0; j < cols; j++) {
printf("Column %d: %d\n", j + 1, col_sum[j]);
}
printf("\nā
Row with maximum sum: Row %d (Sum = %d)\n",
max_row_index + 1, max_row_sum);
printf("ā
Column with maximum sum: Column %d (Sum = %d)\n",
max_col_index + 1, max_col_sum);
return 0;
}
Frequently Asked Questions
1. How do you find the sum of each row in a matrix in C?
Use a loop to iterate through each row, and within each row, use an inner loop to add all elements in that row. Store the result in an array.
2. How do you find the sum of each column in a matrix in C?
Use nested loops where the outer loop iterates over columns and the inner loop iterates over rows, adding each element to the column sum.
3. Can you calculate row and column sums in a single loop?
Yes, you can calculate both row and column sums in the same nested loop as shown in the program above.
4. What is the grand total of a matrix?
The grand total is the sum of all elements in the matrix. It can be calculated by summing all row sums or all column sums.
5. What is the time complexity of finding row and column sums?
The time complexity is O(r Ć c), where r is the number of rows and c is the number of columns.
š” Tip: Row and column sums are often used in data analysis to find marginal totals. They are also used in image processing to calculate brightness sums.