- What a matrix (2D array) is in C programming
- How to declare and initialize a 2D array
- How to find the sum of each row in a matrix
- How to find the sum of each column in a matrix
- Complete code example with step-by-step explanation
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.
A matrix in C is a two-dimensional (2D) array that organizes data in rows and columns.
It's like a table with rows going horizontally and columns going vertically.
In C, a 2D array is declared as dataType arrayName[rows][columns].
This operation is used in many real-world applications, such as:
- Calculating total sales per product category (row sums)
- Finding total monthly revenue across different years (column sums)
- Image processing and data analysis
- Statistical calculations and spreadsheets
💡 Think of it this way: A matrix is like a spreadsheet where each cell stores a value. Row sums add all values across a row, and column sums add all values down a column.
C Program to Find Row and Column Sums
#include <stdio.h>
#define MAX_ROWS 10
#define MAX_COLS 10
int main() {
int matrix[MAX_ROWS][MAX_COLS];
int rows, cols;
int i, j;
// Input dimensions
printf("Enter number of rows (max %d): ", MAX_ROWS);
scanf("%d", &rows);
printf("Enter number of columns (max %d): ", MAX_COLS);
scanf("%d", &cols);
// Validate dimensions
if(rows > MAX_ROWS || cols > MAX_COLS || rows <= 0 || cols <= 0) {
printf("Invalid dimensions!\n");
return 1;
}
// Input matrix elements
printf("\nEnter matrix elements:\n");
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("Element [%d][%d]: ", i+1, j+1);
scanf("%d", &matrix[i][j]);
}
}
// Display the matrix
printf("\nThe matrix is:\n");
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("%5d ", matrix[i][j]);
}
printf("\n");
}
// Calculate and display row sums
printf("\n=== Row Sums ===\n");
for(i = 0; i < rows; i++) {
int rowSum = 0;
for(j = 0; j < cols; j++) {
rowSum += matrix[i][j];
}
printf("Row %d: %d\n", i+1, rowSum);
}
// Calculate and display column sums
printf("\n=== Column Sums ===\n");
for(j = 0; j < cols; j++) {
int colSum = 0;
for(i = 0; i < rows; i++) {
colSum += matrix[i][j];
}
printf("Column %d: %d\n", j+1, colSum);
}
return 0;
}
Sample Output
Enter number of rows (max 10): 3
Enter number of columns (max 10): 3
Enter matrix elements:
Element [1][1]: 1
Element [1][2]: 2
Element [1][3]: 3
Element [2][1]: 4
Element [2][2]: 5
Element [2][3]: 6
Element [3][1]: 7
Element [3][2]: 8
Element [3][3]: 9
The matrix is:
1 2 3
4 5 6
7 8 9
=== Row Sums ===
Row 1: 6
Row 2: 15
Row 3: 24
=== Column Sums ===
Column 1: 12
Column 2: 15
Column 3: 18
Another Example:
Enter number of rows (max 10): 2
Enter number of columns (max 10): 4
Enter matrix elements:
Element [1][1]: 1
Element [1][2]: 2
Element [1][3]: 3
Element [1][4]: 4
Element [2][1]: 5
Element [2][2]: 6
Element [2][3]: 7
Element [2][4]: 8
The matrix is:
1 2 3 4
5 6 7 8
=== Row Sums ===
Row 1: 10
Row 2: 26
=== Column Sums ===
Column 1: 6
Column 2: 8
Column 3: 10
Column 4: 12
Program Explanation
Let's break down the code step by step:
- Include Header File:
#include <stdio.h>includes the standard input/output library. - Define Constants:
#define MAX_ROWS 10and#define MAX_COLS 10set maximum matrix size. - Declare Variables:
int matrix[MAX_ROWS][MAX_COLS];— the 2D arrayint rows, cols;— dimensions of the matrixint i, j;— loop counters
- Input Matrix: Nested loops read values from the user into the matrix.
- Display Matrix: Nested loops print the matrix in tabular format.
- Calculate Row Sums: For each row, we initialize
rowSum = 0and add all elements in that row. The column index varies while the row index remains constant. - Calculate Column Sums: For each column, we initialize
colSum = 0and add all elements in that column. The row index varies while the column index remains constant. - Return:
return 0;indicates successful program execution.
📝 Note: The algorithm has a time complexity of O(rows × cols) because we visit each element once. This is optimal since we must examine every element to calculate the sums.
Step-by-Step Approach
| Step | Action | Explanation |
|---|---|---|
| 1 | Declare 2D array | Create a matrix with rows and columns |
| 2 | Input values | Use nested loops to fill the matrix |
| 3 | Calculate row sums | For each row, add all column values |
| 4 | Calculate column sums | For each column, add all row values |
| 5 | Display results | Print matrix and all sums |
Algorithm to Find Row and Column Sums
- Start
- Read the number of rows and columns
- Read elements into the matrix using nested loops
- For
i = 0torows-1:- Set
rowSum = 0 - For
j = 0tocols-1:rowSum += matrix[i][j]
- Print
rowSum
- Set
- For
j = 0tocols-1:- Set
colSum = 0 - For
i = 0torows-1:colSum += matrix[i][j]
- Print
colSum
- Set
- End
💻 Practice Exercise
Challenge 1: Write a program to find the sum of the diagonal elements of a square matrix.
Challenge 2: Write a program to find the sum of each row and each column for a 3x3 matrix without storing the entire matrix (calculate row sums on input).
🔍 Click to Show Solution for Challenge 1
#include <stdio.h>
int main() {
int matrix[10][10];
int n, i, j;
int diagSum = 0;
printf("Enter the size of square matrix: ");
scanf("%d", &n);
printf("Enter matrix elements:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Calculate diagonal sum (main diagonal)
for(i = 0; i < n; i++) {
diagSum += matrix[i][i];
}
printf("Matrix:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
printf("%5d ", matrix[i][j]);
}
printf("\n");
}
printf("Sum of diagonal elements: %d\n", diagSum);
return 0;
}
🔍 Click to Show Solution for Challenge 2
#include <stdio.h>
int main() {
int matrix[3][3];
int i, j;
printf("Enter 3x3 matrix elements:\n");
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("\nMatrix:\n");
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
printf("%5d ", matrix[i][j]);
}
printf("\n");
}
// Row sums
printf("\nRow Sums:\n");
for(i = 0; i < 3; i++) {
int sum = 0;
for(j = 0; j < 3; j++) {
sum += matrix[i][j];
}
printf("Row %d: %d\n", i+1, sum);
}
// Column sums
printf("\nColumn Sums:\n");
for(j = 0; j < 3; j++) {
int sum = 0;
for(i = 0; i < 3; i++) {
sum += matrix[i][j];
}
printf("Column %d: %d\n", j+1, sum);
}
return 0;
}
Frequently Asked Questions
1. What is the difference between row sum and column sum?
Row sum adds all elements in a specific row (left to right). Column sum adds all elements in a specific column (top to bottom). For a 3x3 matrix, each row sum has 3 elements, and each column sum has 3 elements.
2. Why do we use nested loops for matrix operations?
Matrices are 2D structures, so we need two indices to access elements: one for rows and one for columns. Nested loops allow us to systematically traverse all rows and columns. The outer loop handles rows, and the inner loop handles columns.
3. How can I make my program handle larger matrices?
You can increase the MAX_ROWS and MAX_COLS constants. For dynamic sizing, consider using dynamic memory allocation with malloc().
4. Can I calculate sums without storing the entire matrix?
Yes, you can calculate row sums on the fly as you input data. However, column sums require knowing all rows first, so you'd need to store column sums in an array or store the entire matrix.
5. What is the time complexity of this algorithm?
The algorithm has a time complexity of O(rows × cols) because we visit each element once. This is optimal since we must examine every element to calculate the sums.
💡 Tip: Always validate input dimensions to prevent buffer overflow and ensure your program is robust.