Sum of primary diagonal members of a square matrix using 1 loop only – Computer Sir Ki Class Code Learning #CPP#7521   Sum of primary diagonal members of a square matrix using 1 loop only

Finding sum of primary diagonal (from left top to right bottom) members of a 2D of a square matrix array using one loop only

Learning Objectives

• Understanding summing of elements in a primary diagonal location of a square 2D matrix form array using just one iteration loop.

Source Code

 #include using namespace std; int main() { int arr={{1,2,3},{4,5,6},{7,8,9}}; int sum=0; for(int i = 0; i < 3; i++ ) sum+=arr[i][i]; cout<<"Sum of primary diagonal members = "<

Run Output

Sum of primary diagonal members = 15

Code Understanding

int arr={{1,2,3},{3,4,5},{6,7,8}};
Here is an initialised 3 row and 3 column two dimensional array.

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 < 3; i++ )
This for loop handles the row as well as column index.

sum+=arr[i][i];
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-1loop.cpp, pdiags1.cpp

CSKC| Created: 11-Oct-2019 | Updated: 11-Oct-2019|

×