Print the total sum and sum of all rows and all columns of n by n matrix. How to find the sum of row in a matrix

 

Program to print the total sum, individual sum of each row and column

        To perform any operation on a matrix(multidimensional array), nested loops are used. To know more about nested loops read The nested loops in C++.

        In this code, I have used for loops to perform all the operations on the matrix. First, read the size and matrix elements from the user. Using nested loop access each element and keep on adding to the sum variable.

        To calculate the row-wise sum, make the row_sum variable zero each time before entering the column loop(j). Print the row_sum once the column loop(j) is completely executed.

        Similarly to calculate the column-wise sum, initiate the column loop(j) first make the col_sum variable zero before initiating the row loop(i). Print the col_sum once the row loop(i) is completely executed. 

        Print the final sum. 


Code

#include<bits/stdc++.h>

using namespace std;


int main()

{

int n;                     //variable for no of rows and columns

cin>>n;                //Reading no of rows and columns


int a[n][n];            //declaration of n*n matrix


//This block reads the n*n matrix

for(int i=0; i<n; i++)

{

for(int j=0; j<n; j++)

{

cin>>a[i][j];

}

}


int sum=0;


for(int i=0; i<n; i++)

{

for(int j=0; j<n; j++)

{

sum=sum+a[i][j];

}

}


//This block Calculates and prints sum of all elements in a row

for(int i=0; i<n; i++)

{

int row_sum=0;

for(int j=0; j<n; j++)

{

row_sum=row_sum+a[i][j];

}

cout<<"The row "<<i+1<<" sum is : "<<row_sum<<endl;

}


//This block Calculates and prints sum of all elements in a column

for(int j=0; j<n; j++)

{

int col_sum=0;

for(int i=0; i<n; i++)

{

col_sum=col_sum+a[i][j];

}

cout<<"The col "<<j+1<<" sum is : "<<col_sum<<endl;

}


//Printing final sum

cout<<"The total matrix sum is : "<<sum<<endl;


return 0;

}



Input

3
1 2 3
4 5 6
7 8 9

Output

The row 1 sum is : 6
The row 2 sum is : 15
The row 3 sum is : 24
The col 1 sum is : 12
The col 2 sum is : 15
The col 3 sum is : 18
The total matrix sum is : 45

Post a Comment

0 Comments