How to Find sum of each row and column of matrix in C++

In this article, we are going to learn about How to Find sum of each row and column of matrix in C++. We will take the input from the user for the matrix elements and then we will perform the addition of elements on the matrix rows and columns.

In this example, we are going to add the elements in a row and elements in a column of a given Matrix.This way we will find the sum of each row elements and sum of elements of each column. We will ask the user to enter the values for each index, and once we have the matrices, then we will perform the addition of elements on the matrix.Let us understand this with the help of below code example.

How to Find sum of each row and column of matrix in C++


#include<iostream>
using namespace std;
int main()
{
	int Matrix[10][10];
	int RowSize , ColumnSize;
	int row, col;
	long SumofRowElements = 0;
	long SumofColElements = 0;
	
	
	cout<<"Enter Row and Column Size of the Matrix: ";
    cin>>RowSize>>ColumnSize;

	
	cout<<"Please enter the Elements of the Matrix: ";
    for(row=0; row< RowSize; row++)
    {
        for(col=0; col< ColumnSize; col++)
            cin>> Matrix[row][col];
    }
	
    
    for(row=0; row < RowSize; row++)
    {
        SumofRowElements = 0;
        for(col=0; col < ColumnSize; col++)
        {
            SumofRowElements += Matrix[row][col];
        }
        
        cout<<"The Sum of elements of row "<<row+1<<" = "<<SumofRowElements<<"\n";
    }
						

    for(row=0; row<RowSize; row++)
    {
        SumofColElements = 0;
        for(col=0; col<ColumnSize; col++)
        {
            SumofColElements += Matrix[col][row];
        }
        
        cout<<"The Sum of elements of column "<<row+1<<" = "<<SumofColElements<<"\n";
    }
    return 0;
}

Output

Enter Row and Column Size of the Matrix: 3
3
Please enter the Elements of the Matrix: 1
2
3
4
5
6
7
8
9
The Sum of elements of row 1 = 6
The Sum of elements of row 2 = 15
The Sum of elements of row 3 = 24
The Sum of elements of column 1 = 12
The Sum of elements of column 2 = 15
The Sum of elements of column 3 = 18