Sum of primary diagonal members of a square matrix array
Finding sum of primary diagonal (from left top to right bottom) members of a 2D of a square matrix array
Learning Objectives
- Understanding summing of elements in a primary diagonal location of a square 2D matrix form array using the traditional nested style for loops.
- Understanding calculation of matrix size of one side dimension in terms of numbers of rows or number of columns in a square matrix.
Source Code
|
Run Output
Code Understanding
int arr[3][3]={{1,2,3},{3,4,5},{6,7,8}};
Here is an initialised 3 row and 3 column two dimensional array.
int dim=sqrt(sizeof(arr)/sizeof(arr[0][0]));
being a square matrix type array we can find the array side or dimension by square rooting the whole size divided by size of first member
int sum=0; //Here we initialise variable sum as 0 so that further member value can be added to it
for(int i = 0; i < dim; i++ )
This for loop handles the row index.
for(int j = 0; j < dim; j++ )
This loop handles the column in each row. both the loop travel for same size given by dim.
if(i==j) sum+=arr[i][j];
for each primary diagonal members row count and column count is same. row column count in given example can be seen below
0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2
we can observe above that row and column count is same of primary diagonal which are given by 0,0/1,1/2,2, thus the logic i==j will work
for each element of primary diagonal.
cout<<“Sum of primary diagonal members = “<<sum<<endl;
Here we are simply printing the sum after the looping is over.
Suggested Filename(s): sum-primary-diag.cpp, pdiagsum.cpp
CSKC| Created: 11-Oct-2019 | Updated: 11-Oct-2019|