Sum of each row and row addition of 2D array – Computer Sir Ki Class Code Learning #CPP#1893    ## Sum of each row and row addition of 2D array

Finding the sum of each row and then sum of all members by adding each row addition of a matrix having number values.

## Learning Objectives

• Learning to traverse a 2D Array.
• Successive summing of individual member in a row to give row wise sum in a variable sumr.
• Adding all row sums to get total sum of the array.

## Program Approach

• Add row sum in each of the internal loop.
• After the internal loop, add row sum successively to a new variable sum to finally get the overall array sum.

## Source Code

 #include using namespace std; int main() { int M={{47,75,80},{52,81,76}}; int sumr=0,sum=0; for (int i = 0; i < 2; i++ ) { sumr=0; for(int j = 0; j < 3; j++ ) { sumr+=M[i][j]; } sum+=sumr; cout<<"Sum of row "<

## Run Output

``````Sum of row 1 = 202
Sum of row 2 = 209
sum of all members = 411``````

## Code Understanding

int M={{47,75,80},{52,81,76}};
Here we declare and initialise a 2 row 3 column array/matrix.

int sum=0,sumr=0;
Here we declare variables sum and sumr which are used to store the total array sum and sum of each row respectively. These given an initial values of 0. Later in the loop each member value will be successively added to  the variable to get the final sum of each row in sumr and final sum of all the members in the variable sum.

for (int i = 0; i < 2; i++ )
This out loop for row level traversing.

sumr=0;
This variable shall be made 0 before every internal loop so that every new row sum can be filled in it and previous value doesn’t affect it.

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

This is inner loop for traversing each column member in a row,

sumr+=M[i][j];
Here we reach out to each member M[i][j] of the array using the index variables i and j successively. We pick this value and add to previous value of sumr. Here sumr will be made 0 before the start of internal loop so that new row sum can again be calculated and filled in it.

sum+=sumr;
Here the sum is calculated by adding the sum of each row and hence it is put immediately after the internal loop.

cout<<“Sum of row “<<i+1<<” = “<<sumr<<endl;
This instruction has been put after the internal loop and just before the end of external loop. this is because it has to be printed for every row.

cout<<“Sum of all members = “<<sum<<endl;
This instruction has been put outside the loop as to print the sum after the entire loop operations are complete.

## Common Errors

• Some times student forget to initialise sum with 0 in the beginning and sumr to 0 before the internal loop. This will lead to undetermined values as the first sum will happen to an arbitrary value.

Suggested Filename(s): sum2Dalt.cpp

sunmitra| Created: 24-Dec-2017 | Updated: 23-Nov-2018|

×