# C++ program to find the Sum of each Row and each Column of a Matrix

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

In this tutorial, we will be discussing a program to find the sum of each row and each column for a given matrix.

For this, we will be given with a say A*B matrix. Our task is to traverse through all the elements of the matrix and find the sum of each row and each column of the matrix.

## Example

#include <iostream>
using namespace std;
#define m 7
#define n 6
//calculating sum of each row
void calc_rsum(int arr[m][n]){
int i,j,sum = 0;
for (i = 0; i < 4; ++i) {
for (j = 0; j < 4; ++j) {
sum = sum + arr[i][j];
}
cout << "Sum of the row "<< i << ": " << sum << endl;
sum = 0;
}
}
//calculating sum of each column
void calc_csum(int arr[m][n]) {
int i,j,sum = 0;
for (i = 0; i < 4; ++i) {
for (j = 0; j < 4; ++j) {
sum = sum + arr[j][i];
}
cout << "Sum of the column "<< i << ": " << sum <<endl;
sum = 0;
}
}
int main() {
int i,j;
int arr[m][n];
int x = 1;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
arr[i][j] = x++;
calc_rsum(arr);
calc_csum(arr);
return 0;
}

## Output

Sum of the row 0: 10
Sum of the row 1: 34
Sum of the row 2: 58
Sum of the row 3: 82
Sum of the column 0: 40
Sum of the column 1: 44
Sum of the column 2: 48
Sum of the column 3: 52
Updated on 09-Jul-2020 08:53:58