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

Sum of Each Row and Column in a Matrix using C

📑 On this page:
  • Introduction
  • C Program to Find Row and Column Sums
  • Sample Output
  • Program Explanation
  • Step-by-Step Approach
  • Practice Exercise
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • 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:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Define Constants: #define MAX_ROWS 10 and #define MAX_COLS 10 set maximum matrix size.
  3. Declare Variables:
    • int matrix[MAX_ROWS][MAX_COLS]; — the 2D array
    • int rows, cols; — dimensions of the matrix
    • int i, j; — loop counters
  4. Input Matrix: Nested loops read values from the user into the matrix.
  5. Display Matrix: Nested loops print the matrix in tabular format.
  6. Calculate Row Sums: For each row, we initialize rowSum = 0 and add all elements in that row. The column index varies while the row index remains constant.
  7. Calculate Column Sums: For each column, we initialize colSum = 0 and add all elements in that column. The row index varies while the column index remains constant.
  8. 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
1Declare 2D arrayCreate a matrix with rows and columns
2Input valuesUse nested loops to fill the matrix
3Calculate row sumsFor each row, add all column values
4Calculate column sumsFor each column, add all row values
5Display resultsPrint matrix and all sums

Algorithm to Find Row and Column Sums

  1. Start
  2. Read the number of rows and columns
  3. Read elements into the matrix using nested loops
  4. For i = 0 to rows-1:
    • Set rowSum = 0
    • For j = 0 to cols-1:
      • rowSum += matrix[i][j]
    • Print rowSum
  5. For j = 0 to cols-1:
    • Set colSum = 0
    • For i = 0 to rows-1:
      • colSum += matrix[i][j]
    • Print colSum
  6. 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.

📖 Related Tutorials

  • Two Dimensional Arrays in C
  • Reading and Displaying 2D Arrays
  • More Array Assignments
  • Structure Examples

Previous Topic: -->> Read and Display 2D Arrays   ||   Next topic: -->> Array 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.