Row and Column Sum of Matrix in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Sum of Each Row and Column in a Matrix in C: Program to Find Row and Column Sums

šŸ“‘ On this page:
  • Introduction
  • C Program for Row and Column Sums
  • Sample Output
  • Program Explanation
  • Algorithm
  • Practice Exercise
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • 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:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int rows, cols; — dimensions of the matrix
    • int i, j; — loop counters
  3. Declare Arrays:
    • int matrix[rows][cols]; — the main matrix
    • int row_sum[rows]; — stores sum of each row
    • int col_sum[cols]; — stores sum of each column
  4. Initialize Sum Arrays: Sets all elements of row_sum and col_sum to 0.
  5. Read Matrix: Uses nested loops to read elements into the matrix.
  6. Calculate Row and Column Sums:
    • row_sum[i] += matrix[i][j] — adds the element to the row sum
    • col_sum[j] += matrix[i][j] — adds the element to the column sum
  7. Display Results: Prints the matrix, row sums, column sums, and a combined table with row/column totals.
  8. Calculate Grand Total: Sum of all row sums (or all column sums).
  9. 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:

  1. Start
  2. Read the number of rows (r) and columns (c)
  3. Create row_sum array of size r, initialized to 0
  4. Create col_sum array of size c, initialized to 0
  5. Read r Ɨ c elements into the matrix
  6. For i = 0 to r-1:
    • For j = 0 to c-1:
      • row_sum[i] += matrix[i][j]
      • col_sum[j] += matrix[i][j]
  7. Print the matrix
  8. Print all row sums
  9. Print all column sums
  10. Print the combined table with row and column totals
  11. 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.

šŸ“– Related Tutorials

  • Check if Matrix is Symmetric
  • Sum of Diagonal Elements in Matrix
  • Matrix Addition in C
  • More Array Assignments

Previous Topic: -->> Check if Matrix is Symmetric   ||   Next topic: -->> Function Assignments


šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.