Sum of Each Rows in a Matrix

Here you will find Program to find sum of each row in a matrix i.e., we have to calculate the sum of each row in a given matrix - The Coding Bro.

Sum of Rows

In this post we will be discuss the program to find sum of each row in a matrix i.e., we have to calculate the sum of each row in a given matrix. Also, the required logic is discussed and the source code is written in C++ which is compiled successfully to provide the best results.

Problem Description

Seenu have a fruit shop and arranged the same set of fruits in column and row wise. Seenu needs to find the total number of fruits in each row. Help him to find out.

INPUT & OUTPUT FORMAT:

Input consists of 2 integers and 1 2D-array. Integers correspond to the size of rows and columns.

SAMPLE INPUT & OUTPUT:

3

3

1 2 3

7 3 1

7 4 1

6

11

12

Explaination :

In this we will be discussing the program to find sum of each row in a matrix i.e., we have to calculate the sum of each row in a given matrix. This can be done through using the nested looping. We will declare an empty array with size of row which will store the summation value of each row. Now using the nested loop calculated the sum of each row and store it in sum variable which is declared before with a zero value. After coming out of the loop print the sum value as per the results requirement.

🔎Logic to follow to come-up with the solution :

1. Declare the required sets of variables to use in the code and declare an empty array with size of row which will store the summation value of each row.

2. Input the elements of the matrix using looping system.

3. Now calculate the sum of each row by adding all the elements of that particular row, this can be done using the nested looping as shown in the code.

4. The summation value is stored in the variable named as sum which initially has a value of zero.

5. Print the sum value as output and store the new sum value i.e., new row sum in the declared array by incrementing the array to next position.

6. Hence this way all the sum value of each row is printed.

👨‍💻Let’s write the required code for the problem :

Code :

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 #include using namespace std; int main() { int m, n, row, col, sum = 0, row_ind = 0, col_ind = 0; cin >> m >> n; int row_arr[m]; int i, j; int mat[m][n]; for(i = 0; i < m; i++) { for(j = 0; j < n; j++) { cin >> mat[i][j]; } } int z = 0; for(row=0; row

Sample Test Cases have been passed successfully

If you liked this post, then share this with your friends and if anything is confusing or incorrect then let me know in the comment section.

Thanks from my side, this is Mayank, keep learning and exploring !!

#Coding #Programming #learning #Matrix

Mayank Pathak is the editor and blogger at "The Coding Bro".He loves to codes, learn new technologies, and write the coding solutions and articles for the communities of learners, especiall…