Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Problem Statement
2.
Method 1
2.1.
Algorithm
2.2.
Complexity Analysis 
3.
Method 2
3.1.
Algorithm
3.2.
Complexity Analysis 
4.
Frequently Asked Questions
4.1.
What is printf & scanf in C?
4.2.
What is an array in C?
4.3.
What is a multi-dimensional array in C explained with an example?
4.4.
What is a dynamic array in C?
4.5.
How is ++i different from i++ in C?
5.
Conclusion
Last Updated: Jul 4, 2024
Medium

C program to find sum of each row and columns of a matrix

Author Amit Singh
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In this article, we will discuss a C Program to find the sum of each row and column of a matrix. To reach this goal, we need to have information about arrays in C. 

An array which is of the form 'm * n' is known as a 2-Dimension array or 2-D array. It is also called a matrix. In this case, m is taken for the number of rows, and n is taken for the number of columns.

Here, we are given a 2-Dimensional array, and our task is to find the sum of each row and each column.

Also see: C Static Function and  Tribonacci Series.

Problem Statement

The problem statement is that Here, we are given a 2-Dimensional array, and our task is to find the sum of each row and each column..

 

Sample Input

3 3

1 2 3 4 5 6 7 8 9

Sample Output:

Calculation of Row Sum

Sum of the elements in row 0 is 6.

Sum of the elements in row 1 is 15.

Sum of the elements in row 2 is 24.
 

Calculation of Column Sum

The sum of all the elements in column 0 is 12.

The sum of all the elements in column 1 is 15.

The sum of all the elements in column 2 is 18.

Explanation: 


There are two ways to calculate the sum of each row and column of a matrix:

Recommended topics, Binary to Hex Converter and Short int in C Programming

Method 1

In this C program, firstly, we will declare the M*N matrix and then find the sum of each row and column, and then we will display the result.

Algorithm

  1. Declaration of a 2-D array, i.e., an m * n matrix.
  2. Initialization of the array using two 'for' loops.
  3. Declaration of two variables that will store the sum of each row and column.
  4. Now to calculate the sum of the row, we will use a nested loop.
  5. Keeping the first index of the matrix constant and incrementing the second index to access each element of the row.
  6. Keep on the addition of these elements and display the result after coming out of the inner loop.
  7. Now calculate the sum of the column again using the nested loop.
  8. Now this time, we will increment the first index of the matrix and keep the second index of the matrix constant to access each element of the column.
  9. Keep on adding these elements and display the result after coming out of the nested loop.

 

Implementation 

#include <stdio.h>
int main()
{
    // 'm' is taken for the number of rows, and 'n' is taken for the number of columns
    int m, n;      


    // initialisation of rows and columns by taking input from the user.
    printf( " Enter the required number of rows and columns: \n " );
    scanf( "%d %d" , &m, &n );   
    
    // initialisation of matrix
    int arr[m][n];   
    printf( "Enter the elements of the given matrix: \n" ) ;
    for( int i=0; i<m; i++)     
    {
        for(int j=0; j<n; j++)
        {
            scanf( "%d", &arr[i][j] );
        }
    }
    printf( "\nThe elements in the matrix are \n" );
    for( int i=0; i<m; i++ )      
   {
        for(int j=0; j<n; j++)
        {
            printf( "%d ", arr[i][j] );
        }
        printf( "\n" );
    }
    printf( "\n Calculation of Row Sum \n" );
    for(int i=0; i<m; i++)   
    {
        int rowsum=0;
        for(int j=0; j<n; j++)
        {
            rowsum = rowsum + arr[i][j] ;
        }
        printf( " \n Sum of the elements in row %d is %d \n ", i, rowsum);
    }
    printf( "\n Calculation of Column Sum \n " );
    for( int i=0; i<m; i++ )
    {
        int colsum=0;
        for( int j=0; j<n; j++ )
        {
            colsum = colsum+arr[j][i] ;
        }
        printf( " \n The sum of all the elements in column %d is %d\n ", i, colsum );
    }
    return 0;
}

 

Output:

Complexity Analysis 

Time Complexity: O(n2)

Space Complexity: Constant space.

You can practice by yourself with the help of online c compiler.

You can also read about dynamic array in c.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Method 2

In this C program, firstly, we will declare the M*N matrix and then find the sum of each row and column by making a call to another function, and then we will display the result.

Algorithm

  1. Declaration of a 2-D array, i.e., an M*N matrix.
  2. Initialization of the array using two 'for' loops.
  3. Declaration of two variables that will store the sum of row and column.
  4. Now for the calculation of the row sum, calling a function.
  5. Keeping the first index of the matrix as constant and incrementing the second index to access each element of the row.
  6. Keep on the addition of these elements and then display the result after coming out of the inner loop.
  7. Now for the calculation of the column sum, calling another function.
  8. This time we will increment the first index of the matrix and keep the second index of the matrix constant to access each element of the column.
  9. Keep on adding these elements and display the result after coming out of the nested loop.
     

Program

#include<stdio.h>

// function to calculate the sum of row
void rowSum(int arr[10][10], int m, int n);


// function to calculate the sum of column
void columnSum(int arr[10][10], int m, int n);
 
int main()
{
            // declaration of matrix and its size
  int a[10][10], m,n;                     
           
           // Initialisation of Matrix by taking input from the user
  printf(" \n Please Enter Number of rows and columns : ");
  scanf( "%d %d", &m, &n );
            
            // insertion of elements of matrix
  printf(" \n Please Enter the Matrix Elements: \n ");
  for(int i = 0; i < m; i++)     
   {
    for(int j= 0; j < n; j++)
     {
       scanf( " %d ", &a[i][j] );
     }
   }
   
    printf(" The elements of the matrix are ");
    for(int i = 0; i < m; i++)               // showing the elements of the matrix
   {
    for(int j= 0; j < n; j++)
     {
       printf("%d ",a[i][j]);
     }
   }
    printf("\n Calculation of Row Sum \n");
    rowSum(a, m, n);                           //Function called for row sum
    printf("\n Calculation of Column Sum \n");
columnSum(a, m, n);                    //Function called for column sum


  return 0;
} 


// Function for the calculation of row sum
void rowSum(int arr[10][10], int m, int n)      
{ 
  for(int i = 0; i < m; i++)
   {
       int rsum=0;
   for(int j = 0;j < n; j++)
   {
   rsum = rsum + arr[i][j];   
}
printf("\nThe Sum of Elements of row %d is %d",i+1,rsum );
    }
}


// Function for the calculation of column sum
void columnSum(int arr[10][10], int m, int n)   
{
  for(int i = 0; i < m; i++)
   {
       int csum=0;
   for(int j = 0; j < n; j++)
   {
   csum = csum + arr[j][i];   
}
printf("\nThe Sum of Elements of Column %d is  %d",i+1,csum );
    }
}

 

Output:

You can run this code on online C compiler for better understanding.

Complexity Analysis 

Time Complexity: O(n2)

Space Complexity: Constant space.

Check out this problem - Two Sum Problem

Frequently Asked Questions

What is printf & scanf in C?

printf() and scanf() are library functions that are inbuilt in the C programming language that allows us to perform formatted input and formatted output functions. Both of these functions are defined and declared in stdio.h header file. The 'f' in printf and scanf stands for 'formatted'.

What is an array in C?

Arrays are generally used to store multiple values in a single variable instead of declaring separate variables for each value. To create an array, define the data type (like int ) and specify the name of the array followed by square brackets [].

What is a multi-dimensional array in C explained with an example?

A multi-dimensional array is a type of array with more than one dimension or level. For example, a 2-D array, or 2-Dimensional array, is an 'array' of arrays, meaning it is a matrix of columns and rows (think of a table).

What is a dynamic array in C?

Dynamic arrays are the type of arrays that are resizable and provide random access for their elements. They can be initialized with variable sizes, and their size can be changed later in the program. Dynamic arrays are generally allocated on the heap, whereas VLAs are allocated on the stack.

How is ++i different from i++ in C?

'i++' means that when the code is executing, it will first read it and do the increment (i = i + 1) after it has been read. ‘++i’ means that when the code is executing, it will first do i=i+1 and then read it.

Conclusion

In this article, we have studied how to calculate the sum of each row and columns of a matrix. We discussed two ways to do that. We hope that this article has provided you with the help to enhance your knowledge regarding programming in C language and if you would like to learn more, check out our articles on jump statements in C/C++bitwise operators in C/C++ and C vs C++.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available, Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Merry Learning!

Live masterclass