Run Output
Sum of row 1 = 202
Sum of row 2 = 209
sum of all members = 411
Code Understanding
int M[2][3]={{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.
Notes
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